简体   繁体   中英

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

So I was playing abound in the V8 console and I did

Object.getOwnPropertyNames([])

I expected to get [] as a result, however ["length"]

SO this means that instead of being part of the prototype chain, length is a member property of all Array objects.

Is this a bug, or is there any design or specific reason length is not the part of a prototype chain?

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.

That is not a bug. By definition, Object.getOwnPropertyNames will return all the enumerable and non-enumerable own properties of an object. When it comes to an array, length is an own property but its enumerable property is 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 ).

Further reading: Enumerability and ownership of properties

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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