【发布时间】:2017-05-31 03:25:51
【问题描述】:
首先,这是一个按预期工作的示例:
let a = { foo: 10 }
let b = { bar: 20 }
a.__proto__ = b
// returns value from prototype just fine
a.bar; // 20
这里有一个问题的例子,它不能按预期工作。为什么?
// "a" has no prototype when created this way
let a = Object.create(null);
// "b" has prototype and it is a JS native Object with a whole slew of its native props
let b = {};
// assign "a" a prototype
a.__proto__ = b;
// let's try
a.toString; // undefined
// but...
a.__proto__ .toString; // function toString() { [native code] }
为什么a.toString 会返回undefined,尽管已经分配了具有该属性的原型?
【问题讨论】:
-
a 仍然未定义,原型引用 b。所以 toString 应该返回 undefined
标签: javascript object prototypal-inheritance proto