Context basics in JavaScript

Let's say we have some function func that uses this inside:

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

What does this point to in this function? And we don't know. And JavaScript doesn't know. And the function itself doesn't know. That is, at the moment the function is created, what exactly this points to is not defined. And it will be determined only when this function is invoked.

Let us have some kind of input:

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

Let's bind our function func to this input so that it executes when the input loses focus. Now, at the moment the function is executed, this will point to our input:

let elem = document.querySelector('#elem'); elem.addEventListener('blur', func); function func() { console.log(this.value); // will display 'text' on focus loss }

But after all, we can have not only single input, but several:

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

And to each of these inputs we can bind our function func. In this case, for the first element, this at the time of the function call will point to first, and for the second - to second.

In practice, this means that this inside the function depends on which of the inputs we lost focus on:

let elem1 = document.querySelector('#elem1'); elem1.addEventListener('blur', func); let elem2 = document.querySelector('#elem2'); elem2.addEventListener('blur', func); function func() { console.log(this.value); // will output either 'text1' or 'text2' }

In general, this feature this is very convenient - we create just one function and bind it to any number of inputs. If this did not refer to the element in which the event occurred, then we would not have succeeded - we would have to create our own function with the same code for each input!

enru