Andreas S
Andreas S

Reputation: 461

Javascript OOP & Coffe

I'm trying to understand the way OOP is handled in Javascript and I stumbled upon the way coffescript definies the constructor function and the prototype. Can somebody tell me what's the advantage of this code

Animal = (function() {

  function Animal(name) {
    this.name = name;
  }

  Animal.prototype.move = function(meters) {
    return alert(this.name + (" moved " + meters + "m."));
  };

  return Animal;

})();

compared to this

function Animal(name) {
  this.name = name;
}

Animal.prototype.move = function(meters) {
  return alert(this.name + (" moved " + meters + "m."));
};

Upvotes: 1

Views: 78

Answers (1)

Mark Broadhurst
Mark Broadhurst

Reputation: 2695

The first example has an anonymous self executing function wrapping the Animal object.

In the example given this does not provide an additional encapsulation. However normally you might want to return a more complex object or rely on additional variables which would be declared in the global scope (a bad thing).

Upvotes: 2

Related Questions