首先,这是一个按预期工作的示例:
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
具有该属性的原型被分配给它?