gpt4 book ai didi

javascript - 为什么函数原型(prototype)被重复链接?

转载 作者:数据小太阳 更新时间:2023-10-29 03:48:48 25 4
gpt4 key购买 nike

我是 JavaScript 的新手。我正在阅读 JavaScript 的好部分。它说:

Every function object is also created with a prototype property

所以我做了这样的事情:

function test() {
}

console.log(test.prototype);

使用 Chrome 的开发者工具,我发现输出如下:

enter image description here

我真的对这个输出感到困惑。为什么 constructorprototype 属性再次嵌套在 constructor 中?为什么这会像一样继续下去?我在哪里缺少这个概念?

提前致谢。

最佳答案

函数的 prototype 属性包含对象,当使用 new 运算符创建时,该函数的所有实例都将从该对象继承。所有这些原型(prototype)对象(通常)都有一个指向函数的 constructor 属性——你有循环引用。因此,当 new test() 继承该属性时,(new test).constructor === test 的计算结果为 true

您需要区分函数对象的 prototype 属性和对象继承自的原型(prototype)对象 - 通常称为“内部 [[prototype]] 属性(property)”。

构造函数是一个函数,更不用说是一个Function,并且两者兼有。因此它继承自 Function.prototype 对象 - 其中 constructor 属性表示所有函数均由 Function 构造函数构造。如果您的开发人员控制台会显示 Function 对象的原型(prototype),您就可以看到它们。我认为设置中有一个选项。

因此,著名的“原型(prototype)链”不是关于constructor 和/或prototype 属性,而是关于该对象继承自的原型(prototype)对象:

 function test() {}              new test()
(a Function) (a test instance)
|| ||
|| ||
\/ \/
Function.prototype test.prototype
(a Function, by spec) (an Object)
|| ||
|| ||
\/ \/
Object.prototype Object.prototype
|| ||
|| ||
\/ \/
null null

关于javascript - 为什么函数原型(prototype)被重复链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10812254/

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