Quantcast
Channel: Richard Knop
Viewing all articles
Browse latest Browse all 20

How To Properly Inherit Methods From Prototype

$
0
0

JavaScript is using prototypal inheritance instead of the common class bases inheritance we are all used to from Java or C#. This can be difficult to understand at first. Consider the simple following example:

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

function Cat(config) {
    // call parent constructor
    Mammal.call(this, config);
}
// inherit all methods from Mammal's prototype
Cat.prototype = new Mammal();

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

We have a simple inheritance pattern here. Mammal is a parent class which accepts config as a constructor argument. Cat extends Mammal’s prototype. Everything looks ok but when you run this code in the browser you will see this in the console:

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

The problem is that we calling the Mammal’s constructor twice. First time, when we try to inherit all methods from the Mammal’s prototype in the Cat object. Second time, when creating instance of Cat.

The correct way of inheriting would be:

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

function Cat(config) {
    // call parent constructor
    Mammal.call(this, config);
}
// inherit all methods from Mammal's prototype
Cat.prototype = Object.create(Mammal.prototype);

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

Viewing all articles
Browse latest Browse all 20

Trending Articles