Possible Duplicate:
Use of ‘prototype’ vs. ‘this’ in Javascript?
Advantages of using prototype, vs defining methods straight in the constructor?
I'm learning about prototype in Javascript. One thing I don't quite understand is why should I add a function using CONSTRUCTOR_FN.prototype.METHOD_NAME
convention rather than just using this.METHOD_NAME
in the body of the CONSTRUCTOR
?
I have written this little code to clarify:
function Cat ( name ) {
this._name = name;
this.say = function ( thing ) {
alert( this._name + " says: '" + thing + "'" );
}
}
function Dog ( name ) {
this._name = name;
}
Dog.prototype.say = function ( thing ) {
alert( this._name + " says: '" + thing + "'" );
}
var c = new Cat( "Mitt");
var d = new Dog( "Barak" );
c.say( "War" );
d.say( "No war" );
As far as I can see both the Cat
and Dog
constructors work the same. If I understand from this question correctly, the only difference is that when you add something to the prototype, all objects from that constructor will have it. Is there any other reason?