之前的文章已经讨论了Array.prototype.slice.call(arguments)
的工作原理,但我不明白为什么要使用call
而不是apply
,因为apply
用于类似数组的对象,而call
用于由逗号分隔的对象列表。难道arguments
不是类似数组的对象吗?应该使用apply
而不是call
吧?
之前的文章已经讨论了Array.prototype.slice.call(arguments)
的工作原理,但我不明白为什么要使用call
而不是apply
,因为apply
用于类似数组的对象,而call
用于由逗号分隔的对象列表。难道arguments
不是类似数组的对象吗?应该使用apply
而不是call
吧?
[1, 2, 3, 4, 5, 6, 7] ---- our example arguments
Array.prototype.slice.call(arguments, 2, 5);
在这里,您将传递给切片方法2和5,这些是切片参数,用于指示您想要获取索引为1到索引为4的项。因此,最有可能的是它将是3、4、5。
Array.prototype.slice.apply(arguments, [2, 5]);
x
是一个数组,那么以下内容是相同的:// find the "slice" method of an array and call it with "x" as its "this" argument
x.slice();
// find the "slice" method of an array and call it with "x" as its "this" argument
Array.prototype.slice.call(x);
func.call
的第一个参数是this参数,或者说函数内部的this
值。剩余的参数是函数的参数(在这种情况下没有参数)。slice
方法,则会简单地创建具有相同内容的新数组。这就是我们使用Array.prototype.slice.call(arguments)
时想要做到的,但是,由于arguments
不是一个数组,因此没有slice
方法附加到自身上,我们必须使用这两种方法中的第二种方法来获取一个数组的slice
方法,然后将其应用于不是数组的内容。// find the "slice" method of an array and call it with "arguments",
// which is *not* an array, as its "this" argument
Array.prototype.slice.call(arguments);
apply
而不是call
,arguments
仍然是thisArg
,而不是argsArray
,因此它不会改变任何东西。 翻译:即使您使用apply
代替call
,arguments
是指向thisArg
(函数的上下文对象),而不是argsArray
(参数数组),因此这不会改变任何内容。 - user2357112.call(thisArg, arg0, arg1, ...)
与apply(thisArg, argsList)
。给定的thisArg
值成为被调用函数(slice
)使用的this
值。 - Jonathan LonowskiArray.from()
已经在最近的版本中添加到语言中,部分替代了slice
的使用。 - Jonathan Lonowski