2016-01-13 53 views
1
var father = { 
    b: 3, 
    c: 4 
}; 

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

child.b现在是2,chrome devtools显示孩子有b属性被继承。我该如何解决这个问题,以及为什么它没有被覆盖?如何在这个例子中获得父亲的财产?

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

+0

Object.getPrototypeOf不仅仅是一个“替代”,它是唯一正确的事情。 '__proto__'已弃用,不应再广告。 – Bergi

0

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

Object.getPrototypeOf(child).b