1

Why does "push method" works with object? How that mechanism works underhood?

function MyArray() { }
MyArray.prototype = [];

var arr = new MyArray();
arr.push(1, 2, 3);
console.log(arr); // [1, 2, 3]  in Chrome

enter image description here

sorry for my english. Thanks!

Jim Button
  • 151
  • 1
  • 8

1 Answers1

2

MyArray returns an object, even in Chrome, and uses the methods of Array, via assigned prototypal inheritance. The result of an instance of MyArray is still an object, not an array.

function MyArray() { }
MyArray.prototype = [];

var arr = new MyArray();
arr.push(1, 2, 3);
console.log(arr);                    // { 0: 1, 1: 2, 2: 3, length: 3 }
console.log(typeof arr);             // object
console.log(Array.isArray(arr));     // false
console.log(arr instanceof Array);   // true
console.log(arr instanceof MyArray); // true
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392