4

我试图了解对象创建的工作原理以及使用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

{name: "someValue"}由于对象本身继承自 Object.prototype ,因此断言最后一行代码返回 true 是否正确?对此有更好的解释吗?

4

1 回答 1

2

它的规范 Object.prototype.isPrototypeOf指出 isPrototypeOf 检查链而不仅仅是父链:

重复

  1. 令 V 为 V 的 [[Prototype]] 内部属性的值。

  2. 如果 V 为空,则返回 false

  3. 如果 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.

于 2013-07-25T07:57:00.130 回答