假设,为了解决这个问题,我希望能够在 Javascript 中创建一个函数,将一个数组的所有元素附加到另一个数组。如果您有权访问目标数组,实现此目的的一种方法是:
var destination = [1,2,3];
var source = [4,5];
Array.prototype.push.apply(destination, source);
console.log(destination); // [1,2,3,4,5]
现在,由于 Array.prototype.push.apply 非常丑陋,我想将它别名为更好的东西,例如:
var pushAll = Array.prototype.push.apply;
我应该能够使用两个参数来调用它:上下文(目标)和参数数组(源)。但是,当我尝试使用别名时,会发生这种情况:
pushAll(destination, [6,7]);
TypeError: Function.prototype.apply was called on [object global], which
is a object and not a function
所以很明显apply
函数没有绑定到push
,这促使我尝试这个:
var pushAll = Function.prototype.apply.bind(Array.prototype.push);
pushAll(destination, [6,7]);
console.log(destination); // [1,2,3,4,5,6,7,8]
这显然工作得很好。我的问题是,为什么我必须绑定push方法才能应用? Array.prototype.push.apply 不应该已经绑定到 apply 了吗?为什么用不同的名称调用它会导致在未绑定的上下文中调用它?