Wednesday, May 9, 2018

func.call

Its a built-in function method func.call(context, …args) that allows to call a function explicitly by setting this.

The syntax is


func.call(context, arg1, arg2, ...)

A simple example is below,


1
2
3
4
5
6
7
function say(phrase) {
  alert(this.name + ': ' + phrase);
}

let user = { name: "JavaScript" };

say.call( user, "Hello" ); // Javascript: Hello

Explanation :

1. In line no 7, we have used user as our context and Hello as our argument.

2. You can pass multiple parameters like arg1, arg2 etc.,

3. After executing line no 7, control will move to line no 1 and say method will be executed.


Things to Remember :

Generally, most of the people will get ambiguous for call and apply. To remember this, use mnemonic is "A for array(apply) and C for comma (call).







No comments:

Post a Comment