javascript - Object.create() 的默认行为

标签 javascript object

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

  1. Let V be the value of the [[Prototype]] internal property of V.

  2. if V is null, return false

  3. 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/

相关文章:

javascript - Windows Phone 8 IE scrollTo 不工作

javascript - 使数组对象都具有相同的键

c++ - 如何访问存储在列表中的对象

javascript - 如何在 React 中创建对象的新实例?

javascript - 如何使用其他函数变量?

javascript - Highcharts 折线图 - 某些类别不可见

javascript - 如何向 PHPMyAdmin 添加 Mathjax 支持

javascript - Mocha/应该 'undefined is not a function'

python - 计算类和实例哈希

java - 为什么引用对象的类变量具有优势?而不是存储对象本身