-2

In the following snippets the subclassed array behaves differently from original arrays. Why?

function Arr() {}
Arr.prototype = new Array();

var iArr = new Arr();    
iArr[0] = 9;
iArr[5] = 10;
console.log(iArr.length);
console.log(iArr[0]);
console.log(iArr[5]);
iArr.push(87);
console.log(iArr.length);
console.log(iArr[0]);
console.log(iArr[5]);

results in

0
9
10
1
87
10

while

var iArr = new Array();
iArr[0] = 9;
iArr[5] = 10;
console.log(iArr.length);
console.log(iArr[0]);
console.log(iArr[5]);
iArr.push(87);
console.log(iArr.length);
console.log(iArr[0]);
console.log(iArr[5]);

gives

6
9
10
7
9
10

what I would have expected for the first snippet as well.

I cannot understand why the length property in the first snippet does not change through accessing elements by index.

JeffRSon
  • 10,404
  • 4
  • 26
  • 51

1 Answers1

1

length behaviors only work for objects that have been created by the Array constructor via new Array. that is, length auto-behaviors only work for genuine Array instances. Here, the only Array instance you have is Arr.prototype, which is iArr's prototype parent. iArr was not created by new Array, so it does not get the magic length behaviors.

Setting values on iArr does not manipulate the prototype parent in any way, so your Array instance is unmodified, which means that length is unmodified.

When you call iArr.push, you're not modifying the parent Array instance either, but the ES5 spec for push requires that push set the length property of whatever object is called on:

  1. Call the [[Put]] internal method of O with arguments "length", n, and true.

For an example that works, using ES6 techniques, see Array subclassing with setPrototypeOf

Community
  • 1
  • 1
apsillers
  • 112,806
  • 17
  • 235
  • 239