Web App Development

Inheriting from a parent class without calling its constructor in Javascript

A common way to make a Javascript object inherit from another object is to set it's constructor function's prototype property to an instance of it's parent:
Child.prototype = new Parent();
However this means that the any instance properties of Parent will also be set in the prototype. Take this code for example:
function Animal(){
console.log("Calling Animal constructor function");
this.test = {};
}

function Giraffe(){
console.log("Calling Giraffe constructor function");
}
Giraffe.prototype = Object.create(Animal);

var g = new Giraffe();
var g2 = new Giraffe();
console.log(g.test === g2.test);
When setting the prototype the Parent function is called and the test objects of the two objects are identical as only the reference instead of the whole object is stored with the new instance:
#Program console output:
Calling Animal constructor function
Calling Giraffe constructor function
Calling Giraffe constructor function
true
To avoid this we can use Object.create when inheriting from Animal:
function Animal(){}

function Giraffe(){}
Giraffe.prototype = new Animal();

var g = new Giraffe();
console.log(g instanceof Animal);

function AlternateGiraffe(){}
AlternateGiraffe.prototype = Object.create(Animal.prototype);
g = new AlternateGiraffe();
console.log(g instanceof Animal);
Notice how instanceof still returns true:
true
true
With either way it's also worth setting the prototype.constructor prototype property to the correct function. After setting the prototype it points to the constructor function of the parent:
function Animal(){}
function Giraffe(){}
console.log("Giraffe constructor is Giraffe:", Giraffe.prototype.constructor==Giraffe);
Giraffe.prototype = Object.create(Animal.prototype);
console.log("Giraffe constructor is Giraffe:", Giraffe.prototype.constructor==Giraffe);
console.log("Giraffe constructor is Animal", Giraffe.prototype.constructor==Animal);
Giraffe.prototype.constructor = Giraffe;
console.log("Giraffe constructor is Giraffe", Giraffe.prototype.constructor==Giraffe);
Output:
Giraffe constructor is Giraffe: true
Giraffe constructor is Giraffe: false
Giraffe constructor is Animal true
Giraffe constructor is Giraffe true
John Resig's blog has a minimal classical inheritance example, using an init function and therefore avoiding the problem of using the new keyword

Comments

Daniele Polencic
Nice ;)

Follow me on Twitter
I'm building monitoring tool for site speed and Core Web Vitals.
➔ Start monitoring your website or run a free site speed test