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

so_user
  • 333
  • 3
  • 15

2 Answers2

0

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

Object-Oriented JavaScript - Second Edition [ 1 ]

Alex Char
  • 32,879
  • 9
  • 49
  • 70
  • `Object.getPrototypeOf` is not just an "alternative", it's the only correct thing to do. `__proto__` is deprecated and should no longer be advertised. – Bergi Jan 13 '16 at 16:43
0

This is one way, but you need to read a little bit more about shadowing and inheritance and prototype chain.

Object.getPrototypeOf(child).b
Vitaliy Terziev
  • 6,429
  • 3
  • 17
  • 25