-1
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?

1
  • 4
    Are you confusing Object() with Object.create() ? Commented Dec 21, 2016 at 7:17

1 Answer 1

4

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.