Search code examples
javascriptobjectprototypeprototype-programming

What's the difference between childObj.prototype = Object.create(parentObj.prototype) and childObj.prototype = parentObj.prototype?


I'd like to know the difference between:

childObj.prototype = Object.create(parentObj.prototype)

and

childObj.prototype = parentObj.prototype;

Because both of them I need to call the parent constructor inside the child object to have access to the constructor properties.

I know how Object.create function works, and I notice that the difference is only because It returns a NEW object with the with the parent's prototype. I guess what I'm not understanding is the effect of returning a new object with the parent's prototype.


Solution

  • Your first sample is the correct way to go about it, as it creates a new object with the parentObj.prototype as its [[Prototype]]:

    childObj.prototype = Object.create(parentObj.prototype); // { __proto__: parentObj.prototype }
    

    The second one just sets childObj.prototype to the same object as the parentObj.prototype. This causes some problems:

    function parentObj() {
    }
    
    parentObj.prototype.parentFn = function() { console.log('parent'); };
    
    
    function childObj() {
    }
    
    childObj.prototype = parentObj.prototype;
    
    // here we are writing onto parentObj.prototype as well!!!
    childObj.prototype.childFn = function() { console.log('child'); };
    
    var child = new childObj();
    
    var parent = new childObj();
    
    child.parentFn(); // 'parent'
    parent.childFn(); // 'child' --- this should not happen!!!
    

    In directly assigning the object, we have written onto the parent .prototype.