call method

The call method allows you to call a function with a given context. The first parameter of the method should be the context of the function, and the remaining parameters - the parameters of the function.

Syntax

javascriptfunction.call(context, parameter1, parameter2...);

Example

Let us have an input:

html<input id="elem" value="text">

Let also be given a function that takes three parameters:

javascriptfunction func(param1, param2, param3) {
  console.log(this.value + param1 + param2 + param3);
}

Let's call our function so that this inside the function is equal to our input, and at the same time passing it the numbers 1, 2 and 3:

javascriptlet elem = document.querySelector('#elem');
func.call(elem, 1, 2, 3);

Example

Let a function take no parameters:

javascriptfunction func() {
  console.log(this.value);
}

In this case, when calling this function through call, it is enough to pass only the first parameter with the context:

javascriptlet elem = document.querySelector('#elem');
func.call(elem);

See also

  • the apply method
    that calls a function with a context
  • the bind method
    that binds a context to a function