2016-11-22 4 views
0
<div id="a"></div><br> 
<div id="b"></div> 
<script> 
    function Con(id){ 
     this.id = id; 
     var me = this; 

     x = function(){ // public function 
      console.log(this.id) 
     }.bind(this); 

     this.y= function(){ // public function 
      console.log(me) 
      html = "<a href='javascript:void(0)' id='mycls-"+this.id+"' onclick='x()'>hello-"+this.id+"</a>"; 
      document.getElementById(this.id).innerHTML = html; 
     } 
     this.y(); 
    } 
    var v = new Con("a"); 
    var v1 = new Con("b"); 
</script> 

JavaScriptのコンストラクタを使用しています。私はy public関数の内部にあるリンクからx public関数を呼び出す必要があります。私は適切なIDを取得したいと思うEX:私はそれをコンソールにする必要がありますdivをクリックしている場合、または私はbのdivをクリックしている場合は、それは常にbのみコンソールbをコンソールする必要があります。JavaScriptでイベントハンドラを使用してpublic関数内のpublic関数を呼び出す方法

+0

を私はあなたの質問を理解していないけど、あなたが実現しませんその "x"関数は可変スコープのため今公開されていませんか?それをパブリックにするには、「this.x」にする必要があります。 –

+0

行3のため "b"だけが出力されます。var me = this; * this *は新しく作成されたオブジェクトを指しているので、変数に格納することで常に最新のインスタンス(この場合 "b")を取得します –

+0

this.x.xのような関数を呼び出すと、 TypeError:this.xは関数ではありません(...) –

答えて

0

引数のようにX機能にIDを渡してください: onclick='x("+this.id+")'

x = function(arg){ // public function 
    console.log(arg.id) 
}.bind(this); 

を総符号見つけてください:

<div id="a"></div><br> 
<div id="b"></div> 
<script> 
    function Con(id){ 
     this.id = id; 
     var me = this; 
     x = function(arg){ // public function 
      console.log(arg.id) 
     }.bind(this); 

     this.y= function(){ // public function 
      html = "<a href='javascript:void(0)' id='mycls-"+this.id+"' onclick='x("+this.id+")'>hello-"+this.id+"</a>"; 
      document.getElementById(this.id).innerHTML = html; 
     } 
     this.y(); 
    } 
    var v = new Con("a"); 
    var v1 = new Con("b"); 
</script> 
関連する問題