Well, you should use prototypes because of code reuse and inheritance.
Basically, if you bind a method to the this
keyword, you are providing that method to only that particular instance, while with prototype, you write the method for all instances of that class.
ex:
function Person(name) {
this.name = name;
this.toString = function() {
return this.name;
}
}
var bob = new Person('Bob');
var jim = new Person('Jim');
jim.toString = function() {
return "I have amnesia, I forgot my name!";
};
Now, although bob
and jim
are both persons (instances of the same class), they behave differently, because they have their own set of rules (methods) that they rely on.
If you were to use a prototype:
function Person(name) {
this.setName(name);
}
Person.prototype = {
name : 'default name',
setName : function(name) {
this.name = name;
},
toString : function() {
return this.name;
}
};
var bob = new Person('Bob');
var jim = new Person('Jim');
Person.prototype.toString = function() {
return "I have amnesia, I forgot my name!";
};
Now, all of your persons behave the same.
Using prototypal inheritance is benefic for code reuse and it won't load the memory with unnecessary duplicate things. + Updating classes is muuuch more easy this way.