var father = {
b: 3,
c: 4
};
var child = Object.create(father);
child.a = 1;
child.b = 2;
child.b is now 2, chrome devtools shows that child has b property that is inherited. How do I get to it, and why it is not overriden?
var father = {
b: 3,
c: 4
};
var child = Object.create(father);
child.a = 1;
child.b = 2;
child.b is now 2, chrome devtools shows that child has b property that is inherited. How do I get to it, and why it is not overriden?
Objects in javascript has a link to other Objects called __proto__
. You can get the properties of parent object using this:
var father = {
b: 3,
c: 4
};
var child = Object.create(father);
child.a = 1;
child.b = 2;
console.log(child);//prints Object { a: 1, b: 2 }
console.log(child.__proto__);//prints Object { b: 3, c: 4 }
You can use this secret property for learning purposes, but it's not a good idea to use it in your real scripts because it does not exist in all browsers (notably Internet Explorer), so your scripts won't be portable.
Be aware that
__proto__
is not the same as prototype, since__proto__
is a property of the instances (objects), whereas prototype is a property of the constructor functions used to create those objects. [ 1 ]
I strongly suggest to use Object.getPrototypeOf():
var father = {
b: 3,
c: 4
};
var child = Object.create(father);
child.a = 1;
child.b = 2;
console.log(child);//prints Object { a: 1, b: 2 }
console.log(Object.getPrototypeOf(child));//prints Object { b: 3, c: 4 }
Reference
This is one way, but you need to read a little bit more about shadowing and inheritance and prototype chain.
Object.getPrototypeOf(child).b