In the chapter of Professional JavaScript for Web Developers on OOP, Nicholas Zachas describes a JavaScript inheritance pattern which he refers to as combination inheritance. The basic idea is that methods are inherited via prototype chaining; whereas parent properties are passed on to descendants by calling the parent constructor within the child constructor.
A small example:
function Parent() {
this.parentProperty;
}
Parent.prototype.parentMethod = function() {
console.info(parentProperty);
}
function Child() {
Parent();
}
Child.prototype = new Parent();
He concludes his discussion by saying that "combination inheritance is the most frequently used inheritance pattern in JavaScript."
However, in his following discussion on the prototypal inheritance pattern, he mentions a shortcoming of combination inheritance, namely that the child type invokes the parent constructor twice: once when creating the prototype and then again in the constructor.
My question is why does the combination inheritance pattern suggest extending the prototype by having the child's prototype be an instance of the parent type, why shouldn't it just reference the parent's prototype directly? Using the previous example, why not just do the following:
Child.prototype = Parent.prototype;
1 Answer 1
By doing:
Child.prototype = Parent.prototype;
You are essentially creating a reference to Parent
's prototype, which means any property added to Child
's prototype is now added to Parent
's prototype as well.
On the other hand by doing:
Child.prototype = new Parent();
Child
's prototype inherits all the properties of Parent
via prototype chaining, thus adding a property to Child
's prototype doesn't affect the Parent
's prototype.
Child.prototype = Object.create(Parent.prototype);
The above achieves same thing except it doesn't run the Parent
's constructor function when creating Child
's prototype.
Child.prototype = Object.create(Parent.prototype)
.