[英]How to call object's method from constructor?
var Dog = function(name) { this.name = name; var Dog = function(name){this.name = name; this.sayName(); this.sayName(); } }
Dog.prototype.sayName = function() {
alert(this.name);
}
I'm creating new instance of Dog object Dog('Bowwow')
, but method sayName() is undefined. 我正在创建Dog对象Dog('Bowwow')
新实例,但是方法sayName()未定义。 Why? 为什么?
Or maybe I should do something like (but I can't see difference)... 或者也许我应该做类似的事情(但看不到区别)...
var Dog = function(name) {
this.name = name;
this.sayName();
this.prototype.sayName = function() {
alert(this.name);
}
}
Thank you. 谢谢。
JavaScript is a little dodgy in this area, your code works as long as you call Dog using the new
constructor. JavaScript在这方面有点不可靠,只要您使用new
构造函数调用Dog,您的代码就可以使用。
new Dog("Hello world")
The new constructor makes this
behave like you want it to. 新的构造使得this
行为像你想让它。 Otherwise it is totally different. 否则完全不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.