offline version v3


232 of 264 menu

apply method

The apply 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 second - the array of function parameters.

Syntax

function.apply(context, array of parameters);

Example

Let us have an input:

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

Let also be given a function taking three parameters:

function 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:

let elem = document.querySelector('#elem'); func.apply(elem, [1, 2, 3]);

Example

Let a function take no parameters:

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

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

let elem = document.querySelector('#elem'); func.apply(elem);

See also

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