Search code examples
javascriptjavascript-inheritance

Prototypical inheritance is not working as expected


var oldobj = {
  firstm: function () { console.log("firstm"); },
  secondm: function () { console.log("secondm"); }
};

var newobj= Object(oldobj);

newobj.thirdm = function () { console.log("thirdm"); };

oldobj.fourthm = function () { console.log("4thm"); };

newobj.fifthm = function () { console.log("5thm"); };

oldobj.fifthm(); // logs "5thm" in console

According to prototypical inheritance, the oldobj has no link to newobj functions. But in the above example how is the oldobj able to access fifthm() of newobj?


Solution

  • There's no inheritance here. There's not even two objects.

    var newobj= Object(oldobj);
    

    makes newobj equal to oldobj.

    From the MDN on Object:

    If the value is an object already, it will return the value

    Prototypal inheritance in JavaScript is done very differently. I'd suggest you read this introduction.

    As pointed out by Felix Kling, it's possible that what you wanted was Object.create:

    var newobj= Object.create(oldobj);
    

    Note that this doesn't make classes, it's more a kind of instanciation than an inheritance if you don't define two prototypes.