Jim Button
Jim Button

Reputation: 161

Why push method works on with object?

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!

Upvotes: 1

Views: 58

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386654

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

Upvotes: 2

Related Questions