Function() X Function.call()

Asked

Viewed 116 times

5

When analyzing Javascript/jQuery plugin code, I often see functions being invoked with .call().

I understand that by calling the functions in this way, the first parameter passed is the this (in this case, the function call provider).

What I’d like to know is if this is really the only difference between using variavel.funcao() and variavel.funcao.call().

If this is not the only difference, what are the others? What are the preferred situations to use each of the methods?

2 answers

4


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]);

3

.call() invokes the function in a scope defined by you and allows you to pass the arguments one by one (you can set the scope of the function and pass the parameters at the same time). For example

var person1 = {firstName: 'Jon', lastName: 'Kuperman'};
var person2 = {firstName: 'Kelly', lastName: 'King'};

function say(greeting) {
    console.log(greeting + ' ' + this.firstName + ' ' + this.lastName);
}

say.call(person1, 'Hello'); // Hello Jon Kuperman
say.call(person2, 'Hello'); // Hello Kelly King

The objects person1, person2 are the scope/context/this that you arrow to function say(), and soon after manage to pass the greeting, which is the parameter.

I advise reading this article, it is well explanatory and brings two more ways to set the scope of a function.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.