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.
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.
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);