Binding a context via the call method in JavaScript

So we've covered how this actually works. Let's now look at methods that allow you to force the context in which the function is called (that is, force it to say what this is equal to).

The first method we'll cover is called call. Let's see how it works with an example. Let us have an input:

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

Let's get a reference to this input and write it to the variable elem:

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

Let's now make a function func, inside which we will display this.value to the console:

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

So far, our function doesn't know what this refers to. Now, if we attached it through addEventListener, then yes. But we won't do that. Instead, we simply call our function, telling it that this should be equal to elem.

This is done like this: func.call(elem). This code is equivalent to simply calling the function func like this: func(), only with the condition that this is equal to elem.

So, the syntax of the call method is: function.call(object to write to this). Let's put it all together:

let elem = document.querySelector('#elem'); function func() { console.log(this.value); // shows the input value } func.call(elem);

Given a function:

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

Given three inputs:

<input id="elem1" value="text1"> <input id="elem2" value="text2"> <input id="elem3" value="text3">

Using the call method and the func function, display the value of each of the inputs.

enru