0

I am studying JavaScript's prototype behavior and see a lot of different usages which confuses me. Let's say we have the following constructor functions and prototype definitions.

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

Mammal.prototype.says = function (  ) {
   return this.saying || '';
};

Mammal.prototype.getName = function (  ) {
   return this.name;
};

function Cat(name) {
   this.name = name; //another maybe better way could be Mammal.call(this, name); results in the same
   this.saying = "meow";
}

Cat.prototype = new Mammal();

Cat.prototype.purr = function() {
   return "rrrrrrr";
};

I've seen this kind of examples a lot on the web and in books but it doesn't feel like this is the proper way of doing it. The first problem I have with it, is that the Mammal constructor is called without it's arguments (which are obvious unknown at this point). As a result of that the name property of the new constructed Mammal object is undefined (see image below).

Example 1

In my opinion this property shouldn't even be there because is has no use and pollutes the object model.

My question: Is the above example which are used a lot to explain some of JavaScript's prototype behavior the accepted way of doing this or is it preferable to do the following:

Cat.prototype = Object.create(Mammal.prototype);

Please release me from this burden. Thanks in advance.

Martijn B
  • 4,065
  • 2
  • 29
  • 41
  • Your question has already been answered here http://stackoverflow.com/questions/4152931/javascript-inheritance-call-super-constructor-or-use-prototype-chain – oleq Jan 16 '13 at 11:07
  • Both are valid and acceptable. Your first example is the most widely supported, while `Object.create` is part of ES5 and thus not supported in IE<9. If it is not a problem for you (or you'd use some DOM shim) and you consider the second approach to be more concise, go with it. – Fabrício Matté Jan 16 '13 at 11:16
  • @FabrícioMatté Thanks for your answer. Could you create a answer so I can mark it as answered? – Martijn B Jan 16 '13 at 11:52

0 Answers0