Solving the context problem in JavaScript

In the previous lesson, you saw how the context is lost in the inner function. Let's solve this problem. There are several solutions. Let's take a look at them.

First solution to the problem

The solution is as follows: in the outer function, write this to any variable and this variable will be available in the inner function, like all variables (usually this variable is called self). Thus, we will pass this from the outer function to the inner one:

"use strict"; let elem = document.querySelector('#elem'); elem.addEventListener('blur', parent); function parent() { console.log(this.value); // shows 'text' let self = this; // write this to any variable, for example, to self function child() { console.log(self.value); // shows 'text' } child(); }

Let this code be given:

<input id="elem" value="3"> "use strict"; let elem = document.querySelector('#elem'); elem.addEventListener('blur', func); function func() { alert( square() ); function square() { return this.value * this.value; } }

The author of the code wanted the square of the number from input value to be displayed on the screen when focus was lost. However, for some reason, when focus is lost, an error is generated in the console. Please fix the code author's mistake. Write a text in which you will explain to the author of the code why this error occurred.

Second solution to the problem

There is another solution to the problem. Let's make the function child take a parameter:

function child(param) { // here will be a code }

And when calling this function, we will pass this into it:

function parent() { child(this); // pass the this as parameter function child(param) { // the param variable contains the passed content of this } }

Since the call to child is carried out in the parent function, the passed this points out what we needed. Then the this gets into the param parameter and will be available inside the function in this form.

Here is the final code:

let elem = document.querySelector('#elem'); elem.addEventListener('blur', parent); function parent() { child(this); // passes the this as parameter function child(param) { console.log(param.value); // prints the value of the input } }

Take the code from the previous task and fix the code problem using the second method you learned.

Third solution to the problem

The third solution to the problem is to use arrow functions, which appeared in JavaScript not so long ago. Such functions, among other things, do not have their own context, but retain the context of the parent. Let's fix our problem with an arrow function:

let elem = document.querySelector('#elem'); elem.addEventListener('blur', parent); function parent() { console.log(this.value); // shows 'text' let child = () => { console.log(this.value); // shows 'text' } child(); }

Take the code from the previous task and fix the code problem using the third method you learned.

enru