Yes, it is. The "only" utility of the call
is to pass this to force an execution context followed by the arguments.
I would like to reply more fully, but there is not much more to say I believe :)
From your description you understand the usefulness, but an example is an ancient gambiarra to convert collections of elements that come from for example document.getElementsByTagName
, or document.querySelectorAll
in an array:
var elementos = [].slice.call(colecao);
What it does is call the method .slice
of that array passing to you colecao
as this
, what causes Javascript to treat colecao
as an array and copy it.
Similar to the .call
is the .apply
who does the same but is ready to pass the arguments after the this
one by one, we can pass an array:
function log(teste, a, b, c) {
console.log(this, teste, a, b, c);
}
log.call({
metodo: 'call'
}, 'testeA', 1, 2, 3);
log.apply({
metodo: 'apply'
}, ['testeB', 1, 2, 3]);
// e depois há maneiras mais modernas :)
var arr = [1, 2, 3, 4];
log.apply({metodo: 'apply destructured'}, ['testeC', ...arr]);
Do you know apply? It’s similar to call but has an additional utility.
– bfavaretto
@bfavaretto From what I read before asking the question, the difference lies in the passage of arguments, right? Or there is something else?
– Artur Trapp
Possible duplicate of How to not lose the "this" of the current object and What’s the difference between apply, call and bind methods when calling a function in Javascript?
– Guilherme Nascimento
Yes, that’s the only difference. Is that this passage of the arguments as array opens up new possibilities in relation to call or direct invocation.
– bfavaretto