Object.create()的默认行为

时间:2013-07-25 07:55:13

标签: javascript object

我试图了解对象创建的工作原理以及使用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继承的吗?对此有什么更好的解释吗?

1 个答案:

答案 0 :(得分:2)

Object.prototype.isPrototypeOf的规范声明isPrototypeOf检查链而不仅仅是父:

  

重复

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

  2.   
  3. 如果V为null,则返回false

  4.   
  5. 如果O和V引用同一个对象,则返回true。

  6.   

你的断言是完全正确的。创建的原型链格式为:

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

相关问题