Problem with using ‘new’ for Inheritance
Imagine you have the following block of code.
function Animal() {
this.offspring = [];
}
function Dog() {
}
Dog.prototype = new Animal();
Dog.prototype.constructor = Dog;
var d1 = new Dog();
var d2 = new Dog();
var pup = new Dog();
d1.offspring.push(pup);
d2.offspring; // Does 'd2.offspring' have a pup in it?
Well it turns out that d2, in the above case, does have a pup in it !!!
Why you ask ?
Because when you write ‘d1.offspring.push’, browser will do the following in its search for ‘offspring’ array.
Look up ‘offspring’ in d1 -> No match
Look up ‘offspring’ in Dog.prototype -> Match found
Hence, ‘pup’ is pushed into the offspring of ‘Dog.prototype’ and thus d2 has the same copy?
How do we fix this now?
Look up the code below where we use ‘Object.create’ with the combination of ‘Animal.call’.
function Animal() {
this.offspring = [];
}
function Dog() {
Animal.call(this); // Use Animal.call(this, args) if any arguments
// exist. Else, use 'apply'
}
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;
var d1 = new Dog();
var d2 = new Dog();
var pup = new Dog();
d1.offspring.push(pup); // Dog {offspring: Array[1]}
d2.offspring; // Dog {offspring: Array[0]}
There you go!