2010-04-15 66 views
1

var Dog = function(name){ this.name = name; this.sayName(); }如何从构造函数中调用对象的方法?

Dog.prototype.sayName = function() { 
    alert(this.name); 
} 

我创建狗对象Dog('Bowwow')的新实例,但方法sayName()是不确定的。为什么?

或者,也许我应该这样做(但我看不出差别)...

var Dog = function(name) { 

    this.name = name; 

    this.sayName(); 

    this.prototype.sayName = function() { 
    alert(this.name); 
    } 
} 

谢谢。

+0

你的第一个代码示例很好用。你遇到什么问题?你可以看到它在这里工作:http://jsbin.com/uxevi3 – 2010-04-15 10:22:26

+0

@Philippe Leybaert,请参阅电子商务答案。我忘了使用新的。 – Kirzilla 2010-04-15 10:26:12

回答

5

JavaScript在这方面有点狡猾,只要您使用new的构造函数调用Dog,您的代码就可以工作。

new Dog("Hello world") 

新的构造使得this的行为很像你想让它。否则它是完全不同的。

相关问题