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.

call method with parameters

Now let the function func take some parameters, let's call them param1 and param2:

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

When calling a function via call, you can pass these parameters like this:

func.call(elem, param1, param2);

Let the following code be given:

<input id="elem" value="hello"> let elem = document.querySelector('#elem'); function func(surname, name) { console.log(this.value + ', ' + name + ' ' + surname); } func(); // should output here 'hello, John Smit'

Add the call method to the last line so that 'hello, John Smit' is displayed. The word 'hello' must come from the input value, 'John' and 'Smit' must be function parameters.

enru