Object.prototype.toString.call(),为什么大部分例子用的是call()而不是apply?

Object.prototype.toString.call(), Why in the most part of examples it's used call() instead apply?

我很好奇,因为当我们在大多数示例中访问高级函数时,它总是使用 call() 方法。

示例:

Object.prototype.toString.call();
Array.prototype.slice.call();

是约定俗成还是另有原因?

两者的作用相同,一个可以 pass comma separated arguments,另一个可以 array。我没有看到任何其他区别,如果在 bind 中,您可以在 later context 处使用返回的函数,而内部函数仍然具有外部函数的 scope

基本上 call() 期望参数需要以逗号分隔格式传递,而 apply() 期望参数作为数组。因此,您看到的示例可能不需要将参数作为数组传递。这是一个选择的问题,

一个简单的例子:

Math.max.call(Math, 1,2,3,4,5);
//is same as 
Math.max.apply(Math, [1,2,3,4,5]);

在某些特殊情况下,call/applythis 参数将作为 object 传递,原始参数将被忽略。喜欢,

var x = document.querySelectorAll("div")
Array.prototype.slice.call(x);
//This will convert the nodeList to an array.

上面的示例将访问传递的 this (a nodeList) 的 length 属性 并将构造一个新数组并 return 它. slice to know more about it. And this is how the slice will works的算法你得看内部,我的回答。

.call 等同于 .apply 只要您不传递 this 以外的参数(即第一个参数)。选择一个而不是另一个只是一种惯例。