返回的事件对象覆盖父对象 - javascript,easeljs

时间:2012-11-30 10:00:19

标签: javascript oop easeljs createjs

我正在使用easeljs进行HTML5游戏。

我在类中的方法中调用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 个答案:

答案 0 :(得分:3)

你需要我们关闭来传递对象引用

 var self = this;
 character.onClick = function(){ self.detectClick() };

答案 1 :(得分:1)

范围'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);
 }
}

答案 2 :(得分:0)

或使用简单的代理方法。

function proxy(method, scope) {
    return function() {
        return method.apply(scope, params);
    }
}
character.onclick = proxy(detectClick, this);

答案 3 :(得分: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);
  }
}