Calling Parent's Constructor In JavaScript OOP-Collection of common programming errors

I have created two objects:

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/

  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);
    

Originally posted 2013-11-10 00:09:25.