【发布时间】:2015-11-08 18:02:40
【问题描述】:
我遇到了一个 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();
【问题讨论】:
-
请说明你是如何调用函数的。
-
... 包括您如何创建实例。
-
该函数是从 MatchManager 的另一个方法的 XMLHttpRequest 的回调中调用的,实例化只是
var manager = new MatchManager() -
不要含糊地描述你是怎么称呼它的。提供正确的test case,以便我们重现问题。 (我运行了那个代码,假设你是如何使用它的,你描述的问题没有发生)。
-
@Quentin 添加到问题中;)
标签: javascript oop object properties