javascript - Length of subclassed array -


in following snippets subclassed array behaves differently 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 have expected first snippet well.

i cannot understand why length property in first snippet not change through accessing elements index.

length behaviors work objects have been created array constructor via new array. is, length auto-behaviors work genuine array instances. here, array instance have arr.prototype, iarr's prototype parent. iarr not created new array, not magic length behaviors.

setting values on iarr not manipulate prototype parent in way, array instance unmodified, means length unmodified.

when call iarr.push, you're not modifying parent array instance either, the es5 spec push requires push set length property of whatever object called on:

  1. call [[put]] internal method of o arguments "length", n, , true.

for example works, using es6 techniques, see array subclassing setprototypeof


Comments

Popular posts from this blog

python - TypeError: start must be a integer -

c# - DevExpress RepositoryItemComboBox BackColor property ignored -

django - Creating multiple model instances in DRF3 -