使用array.prototype.push vs array.push

时间:2015-10-27 15:02:21

标签: javascript arrays prototype

我见过人们在javascript中使用两种不同的方法来使用Array对象的不同方法。

我主要使用它:

arr.push(element1, ..., elementN)

但是我看到有人用这个:

Array.prototype.push.apply(this,arguments)

我知道所有JavaScript对象都从其原型继承属性和方法。 Object.prototype位于原型链的顶部。

两种方法之间有什么区别?每种方法何时应该使用?

2 个答案:

答案 0 :(得分:12)

当您有兴趣将.apply()与非真正数组的对象一起使用时,将使用.push()调用。例如,一个jQuery对象实际上并不是一个数组实例,但代码主要维护一个.length属性,足以使它看起来像一个数组,至少为{{ 1}}和其他数组原型方法有关。

对于一个真正的数组实例,没有必要这样做; .push()方法可以通过原型链直接获得。

所以:

.push()

答案 1 :(得分:2)

我假设你在这样的函数中看到了Array.prototype.push.apply(this,arguments)

function foo() {
    arguments.push = function() {
       Array.prototype.push.apply(this,arguments);    
    } 
    arguments.push(1,2,3);
    //.... 
}

这是foo的arguments,它只是一个类似于Array的对象,而不是一个Array,它没有push方法。所以我们应该使用Array.prototype.push.apply(this,arguments)