Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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;
share|improve this question
    
You want this Child.prototype = Object.create(Parent.prototype). –  elclanrs Jul 28 '14 at 2:55
    
@elclanrs: not really; that wouldn't give the child the parent's state; besides that's an example of prototypal inheritance. –  Isaac Kleinman Jul 28 '14 at 3:35
3  
You don't want to set a reference to the parent prototype, because both prototypes would be the same object. What if you want to add properties only to the child prototype? With Object.create you make a prototypical clone, in other words, a new object with its prototype set to the parent's prototype. This is a common idiom, and it is similar to assigning an instance but without calling the constructor function. –  elclanrs Jul 28 '14 at 4:23
    
Ah, I see. Indeed, your alternative is obviously more correct than mine, and it's good to know that it's a "common idiom". Turn your comments into an answer and I'll accept it. –  Isaac Kleinman Jul 28 '14 at 13:24
    
@elclanrs, can you post your comment as an answer please? :) –  Turnerj Dec 17 '14 at 2:29

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.