This question already has answers here:
How does the “this” keyword work?
                                
                                    (22个答案)
                                
                        
                                去年关闭。
            
                    
我正在写一些执行以下操作的JavaScript:


主函数创建一个名为“ currentState”的“ ModelState”实例。
“ currentState”对象创建一个名为“ scene”的“ LabScene”实例。
然后,场景尝试执行对“ currentState”的回调,并将其自身作为参数传递。
我收到以下错误:


未捕获的TypeError:无法读取未定义的属性“推”
在ModelState.dirtyListCallback(Test.js:16)

代码如下:

function main(){
    //load state
    var currentState = new ModelState();
}

function ModelState(){

    this.dirtyList = [];
    //initialize the scene.
    this.scene = new LabScene(this.dirtyListCallback);
}

ModelState.prototype.dirtyListCallback = function(dirtyObject){
    this.dirtyList.push(dirtyObject);
    console.log(this.dirtyList);
};

function LabScene(dirtyListCallback){
    dirtyListCallback(this);
}


我希望currentState对象将场景对象存储在dirtyList数组中。但这没有发生。这是更大的代码库的一部分,在该代码库中,子对象应被其父对象识别为“脏”(需要重新绘制)。任何帮助,将不胜感激。

最佳答案

当您在this中执行dirtyListCallback时,LabScene的范围将是(窗口||全局)。

您需要绑定要在其中执行dirtyListCallback方法的作用域。

this.scene = new LabScene(this.dirtyListCallback.bind(this));

10-07 14:39