offline version v3


233 of 264 menu

bind method

The bind method binds a context to a function. The context should be passed as the first parameter, and the function parameters as subsequent parameters. The method returns a new function, inside which this will be equal to the passed context.

Syntax

function.bind(context, parameter1, parameter2...);

Example

Let us have an input:

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

Let the reference to this input be written into the variable elem:

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

Suppose we also have the following func function:

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

Let's make a new function using bind, which will be a copy of the func function, but this in it will always be equal to elem:

let newFunc = func.bind(elem);

Now the variable newFunc contains a function. Let's call it by passing '1' to the first parameter and '2' to the second:

newFunc('1', '2');

Let's get it all together:

let elem = document.getElementById('elem'); function func(param1, param2) { console.log(this.value + param1 + param2); } let newFunc = func.bind(elem); newFunc('1', '2'); // shows 'text12'

Example

It is not necessary to write the result of bind into a new newFunc function, you can just overwrite func:

let func = func.bind(elem);

See also

  • the call method
    that calls a function with a context
  • the apply method
    that calls a function with a context
enru