我试图了解对象创建的工作原理以及使用 Object.create()
创建的对象的相应原型(prototype)。我有以下代码:
var obj = Object.create({name: "someValue"});
console.log(Object.getPrototypeOf(obj)); // => Object{name: "someValue"}
console.log(obj.constructor.prototype); // => Object{}
// check if obj inherits from Object.prototype
Object.prototype.isPrototypeOf(obj); // => true
断言最后一行代码返回 true 是否正确,因为对象 {name: "someValue"}
本身继承自 Object.prototype?对此有更好的解释吗?
最佳答案
Object.prototype.isPrototypeOf
的规范它指出 isPrototypeOf 检查链而不仅仅是父链:
Repeat
Let V be the value of the [[Prototype]] internal property of V.
if V is null, return false
If O and V refer to the same object, return true.
您的断言是完全正确的。创建的原型(prototype)链格式为:
obj => Object {name:"someValue"} => Object {} => null
/ \
|
\ -- This guy is Object.prototype
您可以通过使用 Object.create
创建对象并将 null 作为参数传递来使用代码验证它。
var obj = Object.create(null);
Object.prototype.isPrototypeOf(obj); //false
在这里,由于我们传递的是 null
而不是对象,它本身没有 Object.prototype 作为原型(prototype),所以我们得到 false
。
关于javascript - Object.create() 的默认行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17852172/