答案已经给出,但我只想分一杯羹。你想要实现的在 JS 的上下文中称为method borrowing,当我们从一个对象中获取一个方法并在另一个对象的上下文中调用它时。采用数组方法并将它们应用于参数是很常见的。让我举一个例子。
所以我们有“超级”散列函数,它以两个数字作为参数并返回“超级安全”散列字符串:
function hash() {
return arguments[0]+','+arguments[1];
}
hash(1,2); // "1,2" whoaa
到目前为止一切都很好,但是我们对上述方法没有什么问题,它是受约束的,只适用于两个数字,这不是动态的,让我们让它适用于任何数字,而且你不必传递数组(如果你仍然坚持,你可以)。好了,废话不多说,我们一起战斗吧!
自然的解决方案是使用arr.join 方法:
function hash() {
return arguments.join();
}
hash(1,2,4,..); // Error: arguments.join is not a function
哦,伙计。不幸的是,这行不通。因为我们调用 hash(arguments) 并且 arguments 对象既是可迭代的又是类数组的,但不是真正的数组。下面的方法怎么样?
function hash() {
return [].join.call(arguments);
}
hash(1,2,3,4); // "1,2,3,4" whoaa
诀窍叫method borrowing.
我们从常规数组[].join. 中借用join 方法,并使用[].join.call 在arguments 的上下文中运行它。
为什么会起作用?
那是因为native方法arr.join(glue)的内部算法非常简单。
几乎“按原样”取自规范:
Let glue be the first argument or, if no arguments, then a comma ",".
Let result be an empty string.
Append this[0] to result.
Append glue and this[1].
Append glue and this[2].
…Do so until this.length items are glued.
Return result.
所以,从技术上讲,它需要 this 并将 this[0]、this[1] ...等连接在一起。它是有意以允许任何类似这样的数组的方式编写的(并非巧合,许多方法都遵循这种做法)。这就是为什么它也适用于this=arguments.