gpt4 book ai didi

javascript - 为什么有些方法有 .prototype 而有些没有?

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

关于 prototype 的问题:为什么有些 Array 方法有 .prototype而其他人则没有?

JavaScript Array method names screenshot

documentation声明“Array.prototype 表示 Array 构造函数的原型(prototype)”。

我试图将此声明与以下理解相协调 prototype是引用父类型的属性,因为这是实现继承的方式。

如果后者为真,那么Array的父类型是什么?谁“拥有”像map()这样的方法和 indexOf()

我的主要问题是第一行的问题。

最佳答案

I am trying to reconcile this statement with the understanding that prototype is a property referring to the parent type, since that is how inheritance is achieved.

没有。与另一个对象(从中继承属性)的原型(prototype)关系是通过一个不可见的链接完成的,有时表示为 [[prototype]]

构造函数上实际存在的 .prototype 属性是该函数构造的所有实例都将从中继承的对象。

所以 Array 对象的原型(prototype)(继承)链看起来是这样的:

                             null
^
|
Object.prototype ---> {hasOwnProperty(), …} // all objects inherit these
^
|
Array.prototype ----> {map(), indexOf(), …} // all arrays inherit these
^
|
{length, 0, 1, 2, …} // an example array
// as if constructed by new Array(5) or [42, 7, 6]

Why do some methods have .prototype and some don't?

.prototype 上可用的函数将被所有实例继承,如果它们是它们的方法,您可以直接调用它们。

直接放在构造函数上的函数,如 Array.isArrayArray.of,不是实例相关的,可以说是“静态”的。您主要使用非数组作为参数来调用它们。

关于javascript - 为什么有些方法有 .prototype 而有些没有?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525673/

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