JavaScript对象无法识别属性

JavaScript Object not recognizing property

本文关键字:识别 属性 对象 JavaScript      更新时间:2023-09-26

我在JS对象上遇到了一个奇怪的错误,它是这样的:

function MatchManager(){
    this.current_m = [];
}
MatchManager.prototype.addMatchBatch = function (array){
    // yes I could do an apply..
    for(var i = 0; i < array.length; i++){
        this.current_m.push(array[i]);
    }
}

但是,当我在MatchManager的实例上调用addMatchBatch时,我得到了Cannot read property 'push' of undefined。这意味着current_m没有被实例识别。

我还尝试在for循环中添加var parent=this;并用parent更改this,但没有成功。

我猜this引用了addMatchBatch函数而不是Instance。。。我该如何克服这一点?

如果有人知道原因,我将不胜感激!

非常感谢!

PS:我正在调用和实例化我的对象,比如:

MatchManager.prototype.getCurrent = function(){
    var options : {
        url : myUrl,
        method: "GET",
        callback: this.addMatchBatch
    };
    AJAXCall(options);
}
var manager = new MatchManager();
manager.getCurrent();
callback: this.addMatchBatch

您将函数作为参数传递,但函数中this的值取决于它被调用的上下文,无论AJAXCall做什么,它都不会在第一个上下文中调用它。

创建一个在正确上下文中调用它的新函数,然后传递该函数。

callback: this.addMatchBatch.bind(this)