gpt4 book ai didi

javascript - 将 Object.create() 的结果作为参数传递给 Object.create() 无法工作

转载 作者:行者123 更新时间:2023-12-02 16:10:37 26 4
gpt4 key购买 nike

var Parent = Object.create(null);

Object.defineProperties(Parent, {
__name: {
value: 'tom'
},
__age: {
value: 26
},
})

var foo = Object.create(Parent); // {} No Properties

为什么Object.create(Parent)无法从Parent获取属性__name和__age

最佳答案

Why can't Object.create(Parent) get the properties __name and __age from Parent

确实,您显然只是通过Object.keys或类似的方式寻找它们,它只显示对象的自己的属性,而不是从其原型(prototype)继承的。

如果您使用 in ("__name"in foo),您将看到该属性存在,如果您访问它,您将获得该值从原型(prototype)开始。

我们不能使用 foo.hasOwnProperty (不是直接使用),因为 Parent 有一个 null 原型(prototype),而不是通常的 对象.原型(prototype)。所以 foo 不会从 Object.prototype 继承通常的东西。不过,我们可以间接使用它:Object.prototype.hasOwnProperty.call(foo, "__name")。这会说 false 因为它不是自己的属性,而是继承的。

这是一个示例,其中包含检测属性及其结果的各种方法(根据我们查看继承属性的方式而有所不同):

var Parent = Object.create(null);

Object.defineProperties(Parent, {
__name: {
value: 'tom'
},
__age: {
value: 26
},
})

var foo = Object.create(Parent);
snippet.log(foo.__name); // tom
snippet.log(foo.__age); // 26

snippet.log("__name" in foo); // true, it's there
snippet.log(Object.hasOwnProperty.call(foo, "__name")); // false, it's inherited
snippet.log(JSON.stringify(Object.keys(foo))); // [] - object.keys only looks at "own" properties
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

回复您的评论:

Why are there no [[proto]] property refer to Parent in foo when debug in devtool

我认为你的意思是__proto__,而不是[[proto]]。它们不是同一件事。 __proto__ 是一个访问器属性,如果存在,则访问对象的[[proto]]。 Chrome 的开发工具会向您显示 __proto__(如果存在)。但 foo 没有。为什么不?因为 __proto__Object.prototype 的一部分(请参阅 §B.2.2.1 of the draft spec ),并且 foo 不会继承 Object.prototype,因为它继承自没有原型(prototype)的 Parent,因为它是通过 Object.create(null) 创建的。

通过使用 Object.getPrototypeOf,我们可以看到 foo 有一个原型(prototype),并且它是 Parent:

var Parent = Object.create(null);

Object.defineProperties(Parent, {
__name: {
value: 'tom'
},
__age: {
value: 26
},
})

var foo = Object.create(Parent);
snippet.log(foo.__proto__ === Parent); // false, foo doesn't have __proto__
snippet.log(Object.getPrototypeOf(foo) === Parent); // true, Parent is foo's prototype
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

关于javascript - 将 Object.create() 的结果作为参数传递给 Object.create() 无法工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30256448/

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