Richard Knop
Richard Knop

Reputation: 83755

Prototypal Inheritance Why Does Child Object Not Inherit Method From Parent Object?

So here is my JavaScript:

http://jsfiddle.net/GPNdM/

I have a Cat object which extends Mammal's prototype. Mammal has run() method. But when I create new Cat object and call run() it tells me it's undefined:

function Mammal(config) {
    this.config = config;
}
Mammal.prototype.run = function () {
    console.log(this.config["name"] + "is running!");
}

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

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

Any idea why?

Upvotes: 0

Views: 69

Answers (1)

Esailija
Esailija

Reputation: 140234

It should be Cat.prototype = Object.create(Mammal.prototype), that's where the methods are, not on Mammal directly.

http://jsfiddle.net/GPNdM/1/

Upvotes: 5

Related Questions