The following bind
method allows you to
permanently bind a context to a function. As a
result, this method returns a new function,
inside which this
will have a
hard-coded value.
Let's look at an 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
function func
:
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 function func
,
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'
in the first
parameter, and '2'
in the second (remember
that elem contains an input with a value equal to
'text'
):
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'
It is not necessary to write the result of bind
into a new function newFunc
, you can simply
overwrite func
. After that, func
will
be the same function as it was, but with a
hard-coded this
:
func = func.bind(elem);
Let the following code be given:
<input id="elem" value="привет">
let elem = document.getElementById('elem');
function func(name, surname) {
console.log(this.value + ', ' + name + ' ' + surname);
}
// Let's write a construct with bind() here
func('John', 'Smit'); // should output here 'hello, John Smit'
func('Eric', 'Luis'); // should output here 'hello, Eric Luis'
Write a construction with the method bind
in the indicated place so that this
inside
the func
function always points to the
input from the elem
variable