0

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?

Community
  • 1
  • 1
AlexStack
  • 13,994
  • 14
  • 68
  • 98
  • No other reason, but it's a better programming pattern and far more efficient when creating many instances. Shouldn't that be enough? – Bergi Oct 12 '12 at 12:51
  • you mean when there are 1000 instances of `Dog`, they all use the same `say()` method while for 1000 instances of `Cat`, we'll have 1000 copies of the `say()` function? – AlexStack Oct 12 '12 at 12:54

2 Answers2

4

Actually yes, there is a difference. When you adding a method or property via prototype you can be sure that this method/property will be created only once and they will be contained in the prototype object. However, if you just add your methods to a function that methods will be cloned with each new instance of your class. Lets say you have 10 object instances from your class. If you use prototype you will have only 1 method for all this 10 instances. And if you added method to a function object itself you will have 10 methods copy.

happyCoda
  • 398
  • 2
  • 2
1

IF the constructor was written by someone else (e.g, a library you downloaded), you may not have access to the constructor to change it without modifying the original code. It is also considered to be better style to use the prototype.

Clay
  • 2,700
  • 2
  • 16
  • 16