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/

2
  • 3
    you're calling it here Cat.prototype = new Mammal(); Commented Jun 7, 2013 at 9:56
  • See the question What is the reason to use the 'new' keyword here? and its answers stating that one should not… Commented Jun 7, 2013 at 10:21

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks... This prototype style inheritance is confusing me a lot. I'm not used to it yet.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.