Wednesday, May 9, 2018

func.apply

Already we saw about call and its expecting comma separated parameters. But in apply we should pass array arguments.

A simple example,


1
2
3
4
5
6
7
8
9
function say(time, phrase) {
  alert(`[${time}] ${this.name}: ${phrase}`);
}

let user = { name: "John" };

let arrayData = ['10:00', 'Hello'];

say.apply(user, arrayData); 

Explanation :

1. We are using apply at line no 9. Here user is our context and arrayData is array arguments for this apply.

2. In the arrayData 10:00 will be considered as time and phrase will be considered as Hello.

3. After executing lie no 9 control moves to line 1 to execute a method say and will print the output.


No comments:

Post a Comment