为什么Array.prototype也是一个Array?

问题描述 投票:0回答:3

我认为每个原型都应该是一个对象。

为什么?

Array.isArray( Array.prototype ) // true

developer.mozilla.org什么也没解释

javascript prototype
3个回答
5
投票

您认为每个原型都是

Object
的假设是不正确的。

console.log(String.prototype)
console.log(Number.prototype)
console.log(Boolean.prototype)
console.log(Array.prototype)
console.log(Object.prototype)

输出:

String {}
Number {}
Boolean {}
[]
Object {}

来自 ECMAScript 语言规范 - 15.4.4 数组原型对象的属性(重点是我的)

Array 原型对象的 [[Prototype]] 内部属性的值为标准内置 Object 原型对象(15.2.4)。

数组原型对象本身就是一个数组;它的[[Class]]是“Array”,并且它有一个length属性(其初始值为+0)和15.4.5.1中描述的特殊[[DefineOwnProperty]]内部方法。


0
投票

尝试在 JavaScript 控制台中输入以下内容:

typeof Array.prototype;

Array.prototype
实际上是一个数组。本页对此有详细说明。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype

这可能与

[]
Array
的简写有关。

所以

Array.prototype
指向
[]
Array.prototype.constructor
指向
function Array() { [native code] }

[].constructor
也指
function Array() { [native code] }

所以猜测,这样做是为了让您可以互换使用

Array
[]

我不确定这就是原因,但这是我最好的猜测。


-1
投票

但只是尽我所能做出贡献。

prototype
旨在为所有Javascript对象添加功能/能力,其中Array是一个Javascript对象。然而,数组是一种特殊的对象。

如果您选中了数组的

typeof
,它将反映为对象。 (来源1

但是,最终,您应该将它们视为数组 ([]),而不是对象本身 ({})。所以数组是一种特殊的对象,因为它是一个 JS 对象,所以它可以访问

prototype
,这使得它可以访问新的方法和属性。 (来源2

这是基于我的初步研究和理解。

© www.soinside.com 2019 - 2024. All rights reserved.