0

HTML5 ゲームにイーゼル js を使用しています。

クラスのメソッド内から onClick を呼び出していますが、イベント オブジェクトが「this」オブジェクトを上書きしているため、他のクラス メソッドまたは変数にアクセスできなくなりました。たとえば、次のようなものがあります(明らかに、これは実際のコードではなく、簡単な図です):

function Book(){

  this.text = "this is the text";

  this.makeText = function(){
            //Define some shapes
            var character = new Container();
            character.addChild(some shapes);
            character.onClick = this.detectClick;
  }

  this.detectClick = function(){
           alert(this.text);
  }
}

したがって、これを実行すると、detectClick メソッドでこれがイベント オブジェクトになるため、未定義のアラートが表示されます。

では、このメソッド内から元のテキストを呼び出すにはどうすればよいでしょうか?

どうもありがとう

4

4 に答える 4

3

オブジェクト参照を渡すにはクロージャーが必要です

 var self = this;
 character.onClick = function(){ self.detectClick() };
于 2012-11-30T10:03:31.963 に答える
1

scope of 'this' は、コードの問題です。以下のコードのようにコードを変更します

 function Book(){

  this.text = "this is the text";
  var that=this;
  this.makeText = function(){
        //Define some shapes
        var character = new Container();
        character.addChild(some shapes);
        character.onClick = that.detectClick;
 }

 this.detectClick = function(){
       alert(this.text);
 }
}
于 2013-07-26T12:30:14.897 に答える
0

わかりました、あなたが本当にする必要があるのは

function Book(){

  this.text = "this is the text";

  this.makeText = function(){
            //Define some shapes
            var character = new Container();
            character.addChild(some shapes);
            character.onClick = this.detectClick.bind(this);
  }

  this.detectClick = function(){
           alert(this.text);
  }
}
于 2012-12-25T20:30:04.420 に答える