0

I have created two objects:

  • Mammal
  • Cat

Cat extends Mammal. Both objects have constructor which takes one parameter called config. I am trying to overwrite Mammals constructor in Cat's constructor but I am getting strange results:

function Mammal(config) {
    this.config = config;
    console.log(this.config);
}

function Cat(config) {
    // call parent constructor
    Mammal.call(this, config);
}
Cat.prototype = new Mammal();

var felix = new Cat({
    "name": "Felix"
});

This prints in the console:

undefined fiddle.jshell.net/_display/:23
Object {name: "Felix"} 

Why is the parent constructor called twice? And why, when it's called the first time, this.config is undefined? I am assigning the property. Could you help me fix this code?

http://jsfiddle.net/DS7zA/

Charles
  • 50,943
  • 13
  • 104
  • 142
Richard Knop
  • 81,041
  • 149
  • 392
  • 552
  • 3
    you're calling it here `Cat.prototype = new Mammal();` – Prinzhorn Jun 07 '13 at 09:56
  • See the question [What is the reason to use the 'new' keyword here?](http://stackoverflow.com/questions/12592913/what-is-the-reason-to-use-the-new-keyword-here) and its answers stating that one should not… – Bergi Jun 07 '13 at 10:21

1 Answers1

1

It's called twice because you call it with Cat.prototype = new Mammal(). You're creating the prototype by copying from an instance of Mammal, rather than from the "prototypical" Mammal.

The correct line would be:

Cat.prototype = Object.create(Mammal.prototype);
Alnitak
  • 334,560
  • 70
  • 407
  • 495