Recently I wrote post on What is Bind method in JavaScript and about What is call() method in JavaScript In this post we will take a look on apply method in JavaScript.
apply() method is exactly the same as call() method with minor difference in passing arguments.
Alike call() method using apply() method also, you can invoke a function on given object. Let us understand with some example. Consider that you have a function GreetingMessage() as following ,
1
2
3
4
|
function
GreetingMessage() {
alert(
"Hello Geek !"
);
};
|
And you have an object Student as following,
1
|
var
Student = {};
|
You can call function GreetingMessage on object Student as following,
1
|
GreetingMessage.apply(Student);
|
As output you should get following output,
Apply() method allows you to invoke function which parameter is array of not fixed length. Apply() method pass arbitrary length array as arguments to function.
Let us consider following example. In below example we are calculating sum of the array in function FindSum().
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
function
FindSum(e) {
var
sum = 0;
for
(
var
i = 0 ; i < arguments.length ; i++) {
sum = sum + arguments[i];
}
return
sum;
};
var
Student = {
};
var
sumOfMarks = FindSum.apply(Student, [12, 45, 11, 56, 189]);
alert(sumOfMarks);
|
Essentially above you are passing dynamic array to apply method. In function you can access passed parameters using arguments. As output you will get sum of passed array,
To summarize,
- apply() method takes at least one parameter.
- First parameter is object on which function to be invoked
- Second parameter onwards get passed to the function to be invoked.
- It passes arbitrary length array to function
This was a brief discussion of apply() method is JavaScript. I hope you find this post useful. Thanks for reading.