Reputation: 16606
var Dog = function(name) { this.name = name; this.sayName(); }
Dog.prototype.sayName = function() {
alert(this.name);
}
I'm creating new instance of Dog object Dog('Bowwow')
, but method sayName() is undefined. 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.
Upvotes: 2
Views: 1864
Reputation: 3700
JavaScript is a little dodgy in this area, your code works as long as you call Dog using the new
constructor.
new Dog("Hello world")
The new constructor makes this
behave like you want it to. Otherwise it is totally different.
Upvotes: 5