-1

I created a normal JS object

var person1 = {
name:"ABCD"
}

And then created another Object person2 as

var person2 = Object.create(person1)

Now in browser console when I type

person1 - it gives me the object definition. But when I type person2 - an empty object is printed (i.e {}) though person2.name returns ABCD.

Any thoughts on what is happening here.

1
  • 1
    name property comes from the prototype Commented Jan 20, 2019 at 8:49

1 Answer 1

2

person2 is empty, since you've never assigned to any of its properties; in the console, you have to expand the __proto__ property to get to the prototype of the object, to see what it inherits from.

enter image description here

When typing code in a script (not in the console), although you can use __proto__ to access the prototype:

var person1 = {
  name:"ABCD"
};
var person2 = Object.create(person1);

console.log(person2.__proto__ === person1);

it's deprecated, it's preferable to use Object.getPrototypeOf:

var person1 = {
  name:"ABCD"
};
var person2 = Object.create(person1);

console.log(Object.getPrototypeOf(person2) === person1);

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.