我试图了解对象创建的工作原理以及使用Object.create()
创建的对象的相应原型。我有以下代码:
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继承的吗?对此有什么更好的解释吗?
答案 0 :(得分:2)
Object.prototype.isPrototypeOf
的规范声明isPrototypeOf检查链而不仅仅是父:
重复
设V为V的[[Prototype]]内部属性的值。
如果V为null,则返回false
- 醇>
如果O和V引用同一个对象,则返回true。
你的断言是完全正确的。创建的原型链格式为:
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作为原型,所以我们得到false
。