在这个例子中如何获得父亲的财产?

时间:2016-01-13 09:12:50

标签: javascript javascript-objects

var father = {
  b: 3,
  c: 4
};

var child = Object.create(father);
child.a = 1;
child.b = 2;

child.b现在为2,chrome devtools显示child具有继承的b属性。我如何达到它,以及为什么不重写?

2 个答案:

答案 0 :(得分:0)

javascript中的对象有一个指向其他对象__proto__的链接。您可以使用以下方法获取父对象的属性:



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 }




  

您可以将此秘密属性用于学习目的,但它不是   最好在真实的脚本中使用它,因为它不存在于   所有浏览器(特别是Internet Explorer),所以你的脚本不会   便携式的。

     

请注意__proto__与原型不同,因为   __proto__是实例(对象)的属性,而   prototype是用于创建的构造函数的属性   那些对象。 [1]

我强烈建议使用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 }




<强>参考

Object-Oriented JavaScript - Second Edition [1]

答案 1 :(得分:0)

这是一种方式,但您需要阅读有关阴影和继承以及原型链的更多内容。

Object.getPrototypeOf(child).b