JavaScript对象无法识别属性

时间:2015-11-08 18:02:40

标签: javascript oop object properties

我对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]);
    }
}

但是,当我在addMatchBatch的实例上致电MatchManager时,我会Cannot read property 'push' of undefined。这意味着实例不会识别current_m。

我还尝试在var parent=this;循环中添加this并将parent更改为for,但无济于事。

我猜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();

1 个答案:

答案 0 :(得分:0)

callback: this.addMatchBatch

您将函数作为参数传递,但其中this的值取决于调用的上下文以及AJAXCall所做的任何内容,它不是在第一个环境中调用它。

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

callback: this.addMatchBatch.bind(this)