What is the difference between using call
and apply
to invoke a function?
var func = function() {
alert(\'hello!\');
};
>
Both call()
and apply()
are methods which are located on Function.prototype
. Therefore they are available on every function object via the prototype chain. Both call()
and apply()
can execute a function with a specified value of the this
.
The main difference between call()
and apply()
is the way you have to pass in arguments into it. In both call()
and apply()
you pass as a first argument the object you want to be the value as this
. The other arguments differ in the following way:
call()
you have to put in the arguments normally (starting from the second argument)apply()
you have to pass in array of arguments.let obj = {
val1: 5,
val2: 10
}
const summation = function (val3, val4) {
return this.val1 + this.val2 + val3 + val4;
}
console.log(summation.apply(obj, [2 ,3]));
// first we assign we value of this in the first arg
// with apply we have to pass in an array
console.log(summation.call(obj, 2, 3));
// with call we can pass in each arg individually
The this
value can be tricky sometimes in javascript. The value of this
determined when a function is executed not when a function is defined. If our function is dependend on a right this
binding we can use call()
and apply()
to enforce this behaviour. For example:
var name = 'unwantedGlobalName';
const obj = {
name: 'Willem',
sayName () { console.log(this.name);}
}
let copiedMethod = obj.sayName;
// we store the function in the copiedmethod variable
copiedMethod();
// this is now window, unwantedGlobalName gets logged
copiedMethod.call(obj);
// we enforce this to be obj, Willem gets logged