无法理解Prototype类的范围

时间:2013-09-23 15:19:26

标签: javascript function class prototype createjs

我正在为我正在使用createjs框架在javascript中制作的游戏编写一个场景结构。我遇到的问题是正确引用原型函数中的原始类。我是javascript的新手,这是我第一次使用原型。我目前的代码如下:

function Intro(p, c){
    this.parent = p;
    var s = new createjs.Stage(c);
    this.stage = s;

    this.queue = new createjs.LoadQueue(false);
    this.queue.installPlugin(createjs.Sound);
    this.queue.addEventListener("complete", this.handleComplete);
    this.queue.loadManifest([{id:"bg", src:"images/Intro/intro_background.png"}]);
}
Intro.prototype.handleComplete = function(event){
    console.log("queue completed - handling...");
    var q = event.target;
    var bg = new createjs.Bitmap(q.getResult("bg"));
    this.stage.addChild(bg);
    this.stage.update();
}

当我到达

  

this.stage.addChild(BG);

它似乎失去了范围,我得到“无法调用方法'addChild'的undefined。

任何帮助将不胜感激! -xv

2 个答案:

答案 0 :(得分:0)

您可以通过更改

来修复范围问题
this.queue.addEventListener("complete", this.handleComplete);

this.queue.addEventListener("complete", this.handleComplete.bind(this));

以便绑定函数的范围是this

顺便说一句,您可能对我的游戏感兴趣,我在其中覆盖了createjs类(https://github.com/Canop/SpaceBullet/tree/master/src)。我想我是以干净的方式处理这个问题的。

答案 1 :(得分:0)

如果你在JS中调用函数,它将被动态绑定。将绑定到this的值取决于您调用它的方式,是否将函数作为构造函数调用以及代码是否以严格模式运行。

在您的情况下,以下行:

this.queue.addEventListener("complete", this.handleComplete);

使您的函数在this绑定到全局对象的情况下运行(在Web浏览器中,全局对象是window对象),或者,如果处于严格模式,this将是未定义。

正如@dystroy建议的那样,使用bind()方法来改变这种行为。主叫:

this.queue.addEventListener("complete", this.handleComplete.bind(this));

导致this内的绑定handleComplete()this中的Intro绑定{。}}。


如果您想更详细地了解它。我强烈建议您阅读Dmitry Soshnikov's blog

相关问题