在Javascript中调用方法
我对Javascript完全陌生,这看起来应该很简单,但我不明白为什么我的代码不起作用。下面是我遇到的问题的一个例子:在Javascript中调用方法,javascript,object,methods,Javascript,Object,Methods,我对Javascript完全陌生,这看起来应该很简单,但我不明白为什么我的代码不起作用。下面是我遇到的问题的一个例子: //Thing constructor function Thing() { function thingAlert() { alert("THING ALERT!"); } } //Make a Thing var myThing = new Thing(); //Call thingAlert method myThing.thingAl
//Thing constructor
function Thing() {
function thingAlert() {
alert("THING ALERT!");
}
}
//Make a Thing
var myThing = new Thing();
//Call thingAlert method
myThing.thingAlert();
创建了一个对象,但我不能调用它的任何方法。在这个例子中,为什么thingAlert()没有被调用?OP可以在自己的时间内这样做,如果他觉得这是最好的答案,他不需要因为你是第一个解决他的问题就接受它。无论如何,您可以添加一些解释,解释为什么需要它;)OP可以在自己的时间内这样做,如果他觉得这是最好的答案,他不需要因为你是第一个解决他的问题就接受它。无论如何,您可以添加一些解释,解释为什么需要它;)
Thing
返回的对象没有任何方法。在构造函数中所做的一切就是创建一个局部函数。该函数在事物
终止后被垃圾收集。它的工作方式与任何其他函数相同。Thing
返回的对象没有任何方法。在构造函数中所做的一切就是创建一个局部函数。该函数在事物
终止后被垃圾收集。它的工作方式与任何其他函数相同。
//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();