The apply
method calls the function with a given this
value and an array-like object as an argument.
apply(thisArg, argsArray)
thisArg
: The this
value on executing the function. It is an optional argument. However, if thisArg
is skipped, the this
value is:
argsArray
: The arguments to be passed to a function. Arguments are passed as an array.
The apply
method returns the value returned by the function.
var number = 10;
function test(...arguments) {
let max = arguments.length ? Math.max.apply(null, arguments) : 0;
return this.number + max;
}
console.log("Calling without thisArg");
console.log( test.apply() ); // 10
let obj = {number : 20};
console.log("Calling with thisArg");
console.log( test.apply(obj)); // 20
console.log("Calling with thisArg and arguments");
console.log( test.apply(obj, [100, 200, 300, 400]) ); // 420
In the code above, we have created a test
function that will return the sum of the number property in the this
object, and the largest value in the arguments passed.
First, we called the test function using the apply
method without the thisArg
argument. In this case, the global object is considered as this
.
Then, we called the test
method by passing obj
as a thisArg
value. Inside the test
function, obj
is considered as thisArg
.
Lastly, we passed thisArg
and arguments to the test
function.
"use strict" // strict mode
var number = 10;
function test() {
return this.number;
}
console.log("Calling without thisArg");
console.log( test.apply() ); // error
In the code above, we have called the test
function without thisArg
. This will result in an error because in strict mode, if we don’t pass the thisArg
to the apply
function, the this
value inside the function is undefined
. When trying to access the this
value(undefined), we will get an error.
call()
andapply()
are identical in functionality. The only difference is thatcall()
accepts a list of arguments; whereas,apply()
accepts a single array of arguments.