4

I'm very curious concerning because when we access to high level functions in the most part of examples always it's used the call() method.

examples:

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

It's for convention or there are other reasons?

3 Answers3

4

Basically call() expects the arguments needs to be passed in a comma separated format, whereas apply() expects the arguments as an array. So the examples that you have seen might not needed the arguments to be passed as an array. This is a matter of choice,

A simple example:

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

And in some special cases the this argument for call/apply will be passed as an object and the original arguments will be ignored. Like,

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

The above sample will access the length property of the passed this (a nodeList) and will construct a new array and return it. You have to read the algorithm of slice to know more about it. And this is how the slice will works internally, An answer by me.

Community
  • 1
  • 1
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
1

Both does the same, in one you can pass comma separated arguments and the other one array. I don't see any other difference, if in bind you could use the returned function at a later context with the inner function still having the outer function's scope.

Thalaivar
  • 23,282
  • 5
  • 60
  • 71
1

.call is equivalent to .apply as long as you don't pass arguments other then this (i.e. the first argument). Chosing one over another is just a convention.

freakish
  • 54,167
  • 9
  • 132
  • 169