gpt4 book ai didi

javascript - 原型(prototype)链无法检索 Function.prototype 中的属性集

转载 作者:行者123 更新时间:2023-12-04 01:09:24 26 4
gpt4 key购买 nike

当我将属性添加到 Function.prototype 时,为什么它会从链中消失?为什么属性 yyy(在属性链中)未定义?

function Shape() { }
Shape.prototype.xxx = 111;
Function.prototype.yyy = 222;

let x = new Shape;

console.log(x.xxx) // 111
console.log(x.yyy) // undefined???

最佳答案

Function.prototype 只在 functions 的原型(prototype)链上,所以它不在你的 x 对象的原型(prototype)链上,因为不是函数。 (是的,这有点令人困惑。)

函数Xprototype 属性用于设置通过new XObject 创建的对象的原型(prototype)。创建(X)

您的Shape.prototype 的原型(prototype)是Object.prototype,而不是Function.prototype。 (Function.prototype 是函数 Shape 的原型(prototype)。)

您的代码创建了两个原型(prototype)链,一个用于函数 Shape,一个用于 Shape.prototype(和 x):

+−−−−−−−−−−−−−−−+        +−−−−−−−−−−−−−−−−−−−−+| Shape         |   +−−−>| Function.prototype | +−−−−−−−−−−−−−−−|   |    +−−−−−−−−−−−−−−−−−−−−+ | [[Prototype]] |−−−+    | [[Prototype]]      |−−−+| prototype     |−−−+    | yyy: 222           |   |+−−−−−−−−−−−−−−−+   |    +−−−−−−−−−−−−−−−−−−−−+   |                    |                              \    +−−−−−−−−−−−−−−−−−−−−+                     \   +−−−−−−−−−−−−−−−−−−−−+     +−−>|  Object.prototype  |                      +−>| Shape.prototype    |    /    +−−−−−−−−−−−−−−−−−−−−+                     /   +−−−−−−−−−−−−−−−−−−−−+   |                    |    | [[Prototype]]      |−−−+                    |    | xxx: 111           |                    |    +−−−−−−−−−−−−−−−−−−−−++−−−−−−−−−−−−−−−+   ||       x       |   |+−−−−−−−−−−−−−−−+   || [[Prototype]] |−−−++−−−−−−−−−−−−−−−+

As you can see, since Function.prototype isn't in x's chain, x.yyy is undefined. But Shape.yyy is, since Shape inherits from Function.prototype:

function Shape() { }
Shape.prototype.xxx = 111;
Function.prototype.yyy = 222;

let x = new Shape;

console.log(x.xxx); // 111
console.log(x.yyy); // undefined
console.log(Shape.yyy); // 222

关于javascript - 原型(prototype)链无法检索 Function.prototype 中的属性集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65340223/

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