【问题标题】:Uncaught ReferenceError: "method" is not defined未捕获的 ReferenceError:未定义“方法”
【发布时间】:2014-09-27 10:20:50
【问题描述】:

我创建了一个 javascript 对象

var Article = function(data) {
    this.foo = data,
    this.get_more_data = function() {
        // do something, get a response
        show_data(response);
    },
    this.show_data = function(bar) {
        //do something with bar;
    }
};

在没有这个的情况下编写方法 show_data 时效果很好。但是在对象之外无法访问它。有了这个。我从 Chrome 控制台收到“未捕获的 ReferenceError”。

这是为什么?

谢谢。

【问题讨论】:

  • 你是怎么调用这个方法的?
  • 错误仅发生在上面的代码上,甚至没有从对象外部调用 show_data。我在 var article = new Article(value); 之后从我的代码中调用 article.get_more_data;
  • 也许您应该使用分号而不是冒号? this.foo = 数据;等等?

标签: javascript object methods referenceerror


【解决方案1】:

您应该将show_data 作为this 的方法调用,而不是作为作用于当前上下文的函数:

var Article = function(data) {
    this.foo = data,
    this.get_more_data = function() {
        // do something, get a response
        this.show_data(this.foo);
    },
    this.show_data = function(bar) {
        console.log(bar);
    }
};

【讨论】:

  • 谢谢。我实际上并没有在我的代码上使用 echo ,只是我的问题示例代码中的一个错字。哎呀。
猜你喜欢
  • 2018-06-21
  • 2023-01-23
  • 2016-11-03
  • 2011-01-05
  • 2016-01-02
  • 2013-10-06
  • 2016-12-17
相关资源
最近更新 更多