【问题标题】:Calling a method in Javascript在 Javascript 中调用方法
【发布时间】:2012-12-13 14:18:51
【问题描述】:

我对 Javascript 完全陌生,这看起来应该很简单,但我不明白为什么我的代码不起作用。这是我遇到的问题的一个示例:

//Thing constructor
function Thing() {
    function thingAlert() {
        alert("THING ALERT!");
    }
}

//Make a Thing
var myThing = new Thing();

//Call thingAlert method
myThing.thingAlert();

创建了一个对象,但我不能调用它的任何方法。为什么在这个例子中,thingAlert() 没有被调用?

【问题讨论】:

  • Thing 返回的对象没有任何方法。您在构造函数中所做的只是创建一个 local 函数。该函数在Things 终止后被垃圾回收。它的工作方式与任何其他功能相同。

标签: javascript object methods


【解决方案1】:
//Thing constructor
function Thing() {
    this.thingAlert = function() {
        alert("THING ALERT!");
    };
};
// you need to explicitly assign the thingAlert property to the class.
//Make a Thing
var myThing = new Thing();

//Call thingAlert method
myThing.thingAlert();

【讨论】:

  • 如果OP认为这是最好的答案,他可以在他自己的时间这样做,他不需要仅仅因为你是第一个解决他的问题的人就接受它。无论如何,您可以添加更多关于为什么需要它的解释;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-09
  • 2012-09-25
  • 2013-05-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多