简体   繁体   English

为什么length是Array属性而不是Array.prototype链

[英]Why is length a property of `Array` not `Array.prototype` chain

So I was playing abound in the V8 console and I did 所以我在V8控制台中玩的很多,

Object.getOwnPropertyNames([])

I expected to get [] as a result, however ["length"] 我期望得到[]作为结果,但是["length"]

SO this means that instead of being part of the prototype chain, length is a member property of all Array objects. 因此,这意味着length不是所有原型对象的一部分,而是所有Array对象的成员属性。

Is this a bug, or is there any design or specific reason length is not the part of a prototype chain? 这是一个错误,或者是有任何设计或特殊原因length是不是一个原型链的一部分吗?

Prototype properties are shared across objects. 原型属性在对象之间共享。 So if length is put on prototype, all the array objects will have same length, which is wrong. 因此,如果将长度放在原型上,则所有数组对象将具有相同的长度,这是错误的。 Length signifies number of elements in current array and should remain property of self. 长度表示当前数组中的元素数,应保留为self的属性。

That is not a bug. 那不是错误。 By definition, Object.getOwnPropertyNames will return all the enumerable and non-enumerable own properties of an object. 根据定义, Object.getOwnPropertyNames将返回对象的所有可枚举和不可枚举的自身属性。 When it comes to an array, length is an own property but its enumerable property is false. 当涉及数组时,length是一个自己的属性,但其可枚举的属性为false。 That's the reason why it is getting included in the result. 这就是为什么它被包含在结果中的原因。

you can test it with the following snippet, 您可以使用以下代码段对其进行测试,

console.log(Object.getOwnPropertyDescriptors([]));

The above code will return the descriptors of all the own properties. 上面的代码将返回所有自己属性的描述符。 Inspect it, you will get to know about its enumerable property. 检查它,您将了解它的可枚举属性。

Because it is not enumarable ( Object#propertyIsEnumerable ). 因为它不可枚举( Object#propertyIsEnumerable )。

Further reading: Enumerability and ownership of properties 进一步阅读: 可枚举性和财产所有权

 console.log([].propertyIsEnumerable('length')); 

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

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