What are the differences between these three patterns of "class" definitions in JavaScript?

Posted by user1889765 on Stack Overflow See other posts from Stack Overflow or by user1889765
Published on 2012-12-09T17:02:24Z Indexed on 2012/12/09 17:03 UTC
Read the original article Hit count: 170

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(){}

});

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about backbone.js