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

How to get the property of father in this example?

本文关键字:何获得 父亲 财产      更新时间:2023-09-26
var father = {
  b: 3,
  c: 4
};
var child = Object.create(father);
child.a = 1;
child.b = 2;

child.b 现在是 2,Chrome devtools 显示 child 具有继承的 b 属性。我如何访问它,为什么它没有被覆盖?

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__是实例(对象(的属性,而 原型是用于创建的构造函数的属性 那些对象。[ 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 }

参考

面向对象的 JavaScript - 第二版 [ 1 ]

这是一种方法,但你需要阅读更多关于阴影和继承以及原型链的信息。

Object.getPrototypeOf(child).b