2016-12-19 36 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/ –

相关问题