在这个例子中如何得到父亲的属性?
How to get the property of father in this example?
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__
的对象有一个 link。您可以使用以下方法获取父对象的属性:
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 ]
我强烈建议使用 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.getPrototypeOf(child).b
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__
的对象有一个 link。您可以使用以下方法获取父对象的属性:
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 ]
我强烈建议使用 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.getPrototypeOf(child).b