javascriptinheritance

difference b\w clsParent.prototype and object.create(clsParent.prototype)


how can i do prototypal inheritance in javasciript. usually i do by this and

 derivedFn.prototype = object.create(clsParent.prototype)

but today i got we can also do this the result is same so what is the differce

derivedFn.prototype = clsParent.prototype

For example

function clsParent() {
    this.myName = "faizan"
    this.getMyName = function() {}
}
clsParent.prototype.aProp = "property in prototype"

function clsChild() {
    this.Fname = "abr"
}

clsChild.prototype = clsParent.prototype; //what is the difference
//Object.create(clsParent.prototype); 
// what is the difference if i do inheritance by this
var myObj = new clsChild();
console.log(myObj.myName);
console.log(myObj.aProp);

code is given please clarify me the difference of these two ways inheritance


Solution

  • When you say

    clsChild.prototype = clsParent.prototype;
    

    You are making both the clsChild and clsParent's prototypes the same. So, if you make changes to clsChild.prototype, the changes will be visible in any objects created with new clsParent() as well.

    Try,

    clsChild.prototype.a = 1000;
    console.log(new clsParent().a);
    // 1000
    

    But when you do Object.create(clsParent.prototype), it will create a brand new object which extends from clsParent.prototype. So, making changes to clsChild.prototype will not affect clsParent.prototype.

    Suggestion:

    It is usually a bad idea to store a property in the prototype, since it will be shared by all the instances. You should do this only if your usecase demands it.

    clsParent.prototype.aProp = "property in prototype"; // Don't do this