What are the differences between these three patterns of "class" definitions in JavaScript?
- by user1889765
Are there any important/subtle/significant differences under the hood when choosing to use one of these three patterns over the others? And, are there any differences between the three when "instantiated" via Object.create() vs the new operator?
The pattern that CoffeeScript uses when translating "class" definitions:
Animal = (function() {
function Animal(name) {
this.name = name;
}
Animal.prototype.move = function(meters) {
return alert(this.name + (" moved " + meters + "m."));
};
return Animal;
})();
and
The pattern that Knockout seems to promote:
var DifferentAnimal = function(name){
var self = this;
self.name = name;
self.move = function(meters){
return alert(this.name + (" moved " + meters + "m."));
};
return {name:self.name, move:self.move};
}
and
The pattern that Backbone promotes:
var OneMoreAnimal= ClassThatAlreadyExists.extend({
name:'',
move:function(){}
});