gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:18:41 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com