简体   繁体   English

为什么Array.prototype是一个数组?

[英]Why Array.prototype is an Array?

I thought every prototype should be an object. 我认为每个原型都应该是一个对象。

why? 为什么?

Array.isArray( Array.prototype ) // true Array.isArray(Array.prototype)// true

developer.mozilla.org explains nothing developer.mozilla.org什么都没解释

Your assumption that every prototype is an Object is not correct. 您假设每个原型都是Object是不正确的。

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

Output: 输出:

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

From the ECMAScript Language Specification - 15.4.4 Properties of the Array Prototype Object (emphasis mine) 来自ECMAScript语言规范 - 15.4.4数组原型对象的属性 (强调我的)

The value of the [[Prototype]] internal property of the Array prototype object is the standard built-in Object prototype object (15.2.4). Array原型对象的[[Prototype]]内部属性的值是标准的内置Object原型对象(15.2.4)。

The Array prototype object is itself an array ; Array原型对象本身就是一个数组 ; its [[Class]] is "Array", and it has a length property (whose initial value is +0) and the special [[DefineOwnProperty]] internal method described in 15.4.5.1. 它的[[Class]]是“Array”,它有一个length属性(初始值为+0)和15.4.5.1中描述的特殊[[DefineOwnProperty]]内部方法。

Try typing this into your javascript console: typeof Array.prototype; 尝试在javascript控制台中输入: typeof Array.prototype;

The Array.prototype is actually an Array. Array.prototype实际上是一个Array。 Which is detailed on this page. 本页详细介绍了这一点。

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

It probably has something to do with the Fact that [] is shorthand for Array . 它可能与事实有关, []Array简写。

So Array.prototype points to [] . 所以Array.prototype指向[] Array.prototype.constructor points to function Array() { [native code] } Array.prototype.constructor指向function Array() { [native code] }

[].constructor also points to function Array() { [native code] } [].constructor也指向function Array() { [native code] }

So at a guess, it is done this way so that you can user Array and [] interchangably. 所以在猜测时,它是以这种方式完成的,这样你就可以互相使用Array[]

I dont know for sure this is the reason, but thats my best guess. 我不确定这是原因,但这是我最好的猜测。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM