【问题标题】:JavaScript Object not recognizing property [duplicate]JavaScript对象无法识别属性[重复]
【发布时间】: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


【解决方案1】:
callback: this.addMatchBatch

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

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

callback: this.addMatchBatch.bind(this)

【讨论】:

  • 谢谢!成功了 ;)
猜你喜欢
  • 2021-03-28
  • 2018-12-09
  • 2011-12-26
  • 2014-03-04
  • 2022-09-28
  • 1970-01-01
  • 2018-03-11
  • 2017-07-28
  • 2021-07-21
相关资源
最近更新 更多