Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/384.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 理解原型类的范围有困难_Javascript_Function_Class_Prototype_Createjs - Fatal编程技术网

Javascript 理解原型类的范围有困难

Javascript 理解原型类的范围有困难,javascript,function,class,prototype,createjs,Javascript,Function,Class,Prototype,Createjs,我目前正在为我正在用javascript和createjs框架制作的游戏编写一个场景结构。我遇到的问题是在原型函数中正确引用原始类。我对javascript比较陌生,这是我第一次使用prototype。我目前的代码如下: function Intro(p, c){ this.parent = p; var s = new createjs.Stage(c); this.stage = s; this.queue = new createjs.LoadQueue(

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

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();
}
当我到达

本阶段添加儿童(bg)

它似乎失去了作用域,并且我得到“无法调用未定义的方法'addChild'

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

您可以通过更改

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

因此绑定函数的范围是
this


顺便说一句,你可能会对我的游戏感兴趣,在这个游戏中我覆盖了createjs类()。我认为我以一种干净的方式处理了这个问题。

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

在您的情况下,请使用以下行:

this.queue.addEventListener("complete", this.handleComplete);
使函数在绑定到全局对象(在web浏览器中,全局对象是一个
窗口
对象)的
下运行,或者,如果在严格模式下,
将不定义此

按照@dystroy的建议,使用
bind()
方法更改此行为。调用:

this.queue.addEventListener("complete", this.handleComplete.bind(this));
使
handleComplete()
中的
this
绑定到与
Intro
中相同的
this



如果您想更详细地了解它,我强烈建议您阅读。

如果您需要的兼容性低于internet explorer 9,那么可以看看jQueries.proxy()。它也有同样的功能。由于他使用createjs,我怀疑他是否担心与IE8的兼容性。非常感谢,我一定会看看您在游戏中是如何处理事情的!
this.queue.addEventListener("complete", this.handleComplete.bind(this));