2016-12-19 33 views
1

爲什麼「推送方法」與對象一起工作?這個機制如何運作?爲什麼推式方法與對象一起工作?

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

對不起我的英語。謝謝!

+0

數組對象太 –

+0

你是原型分配到一個數組,然後推到數組...? – Li357

+0

'MyArray' *是一個數組,因爲您明確表示您希望它是通過'prototype'構造的。 –

回答

2

即使在Chrome中也會返回對象,並使用Array的方法,通過指定的prototypal inheritance。 的實例的結果仍然是一個對象,而不是數組。

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

+0

謝謝!但我認爲,這個問題更深入 –

+0

@JimButton,你是什麼意思*更深*? –

+0

例如,「concat method」不工作:https://jsfiddle.net/f8r6j24p/ –

相關問題