Function () X Function.call () [duplicate]

5

When parsing Javascript / jQuery plugins, I usually see functions being invoked with .call() . Home I understand that by calling functions in this way, the first parameter passed is this (in this case, the function call provider). What I would like to know is if this is really the only difference between using variavel.funcao() and variavel.funcao.call() .

If that is not the only difference, what are the others? What are the preferred situations for using each method?

    
asked by anonymous 25.08.2017 / 19:43

2 answers

4

Yes, it is. The "unique" utility of call is to pass this to force an execution context followed by arguments.

I would like to respond more fully, but there is not much else to say I believe:)

By your description you understand the utility, but an example is an old 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 this does is call the .slice method of this array by passing it colecao to this , which causes JavaScript to treat colecao as an array and copy it.

Similar to .call is .apply that does the same but instead of passing arguments after 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]);
    
25.08.2017 / 19:48
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 person1, person2 objects are the scope / context / this you arrow to function say() , and then you can pass greeting , which is the parameter.

I advise you to read this article , it is very explanatory and brings two more ways to setar the scope of a function.

    
25.08.2017 / 19:52