简体   繁体   中英

Do array instance and Array.prototype share a single length property?

According to the ECMAScript spec, Array instances, which are exotic objects, inherit properties from the Array prototype object ( ref ). One of such properties is a well-known length . Changing it directly on an instance may result in removing certain index-keyed properties ( ref ).

On the other hand, as it is said elsewhere with respect to ordinary objects, prototype's data properties are not inherited for the purposes of set access. It means an attempt to set a property on a instance that has not such a key among its own properties keys causes creating a new own property with this key whether a prototype knows this key or not.

Due to I can't find a similar notion but conernced with Array exotic objects, I wonder what should happen when we doing something like this:

let arr = [0, 1, 2];
arr.length = 1;

Was an own property defned on the instance with the prototype's one keeping untouched or are we tinkering with the same length here (that of the prototype's)?

No, array instances do not share their length property with Array.prototype . These are distinct properties.

First of all, the specification indicates that Array.prototype is itself an Array -- which is why it has a length property. See Properties of the Array Prototype Object :

  • is an Array exotic object and has the internal methods specified for such objects.
  • has a "length" property whose initial value is +0

Secondly, when arrays a constructed, like with the Array function, the steps in ArrayCreate are executed:

ArrayCreate ( length [, proto ] ):

[...]
6. Perform ! OrdinaryDefineOwnProperty( A , "length" , PropertyDescriptor { [[Value]]: ( length ), [[Writable]]: true , [[Enumerable]]: false , [[Configurable]]: false }).

This leaves no doubt that every constructed array has its own length property.

As an illustration, we can modify Array.prototype.length from its default value of 0 to another value, and then see that this does not influence the value of length of an instance that is created later:

 console.log(Array.prototype.length); // 0 Array.prototype.length = 1; console.log(Array.prototype.length); // 1 console.log(Array().length); // 0

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