this object advantage in JavaScript

From what has been said before, the special advantage of this is not yet obvious. Indeed, inside the handler function, our element will be available anyway - after all, the variable elem will be global for our function func:

let elem = document.querySelector('#elem'); elem.addEventListener('click', func); function func() { // elem variable with our element is available here }

And, it is easy to figure out that the content of this and the content of the variable elem in our case are equal:

let elem = document.querySelector('#elem'); elem.addEventListener('click', func); function func() { console.log(elem === this); // shows true }

What is the special advantage of this? It manifests itself when we have multiple elements, and the same function is attached to each.

Let's look at an example. Let's say we have 3 buttons:

<input id="button1" type="submit" value="text1"> <input id="button2" type="submit" value="text2"> <input id="button3" type="submit" value="text3">

Get references to them in variables:

let button1 = document.querySelector('#button1'); let button2 = document.querySelector('#button2'); let button3 = document.querySelector('#button3');

Bind the same function to these buttons:

button1.addEventListener('click', func); button2.addEventListener('click', func); button3.addEventListener('click', func);

And inside the function we will display this.value:

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

It turns out that we have three buttons. Pressing each button will call the function func. In this case, with each click, this will contain a reference to the button in which the event occurred.

That is, each press will output to the console value of the button that was pressed, but this will be done by the same function func! That's the advantage of using this.

Given 5 paragraphs with some texts. By clicking on any paragraph, write an exclamation mark at the end of its text.

Given 3 inputs, in which some numbers are written. On loss of focus in any of the inputs, square the number standing in it.