Lexical this in ES-6


Code for this and several other ES-6 features can be found in my github
The root cause for most of the scoping issues/confusions/bugs in Javascript is its difficult to comprehend working of scope. For someone who comes from a language like Java, scope works very differently. In Javascript, every function has its own scope. So, when a function is executed within another function, the “this” keyword outside the child function has a different meaning vs the “this” keyword inside the child function.
Consider the following example:

var fn = function() {    
this.a = 5;    
setTimeout(function(){        
    console.log('value of a = ' + this.a);    },0); 
}();
A callback function is passed as parameter to the 

setTimeOut 

function.
This is executed inside another function called

fn
This basically means, the fn function has a scope which is different from the scope of the function passed as parameter to the the setTimeOut function. Hence the “this” keyword has completely different meaning in both the cases. As a result, the “this” keyword in the inner function will not have a property called “a” in its scope.
The output in this case will be as follows:

value of a = undefined.
One way to deal with this, would be to assign the value of “this”(the current scope) to a different variable. Since the variable’s meaning will not change and all the child functions executed within the parent function can have access to it, the scope can be accessed from the child function as follows:

var fn = function() {    
this.a = 5;    
var that = this;
setTimeout(function(){       
     console.log('value of a = ' + that.a );    },0); 
}();
Here, “that” variable’s meaning is not going to change like “this”. Hence the output would be:

//value of a = 5
However, a better way to assign the scope reassignment is to use the ES-6 Arrow functions (explained previously).
The advantage of arrow functions is that, they don’t have a scope of their own. Hence an arrow function’s scope will be that of its enclosing function.

var fn = function() {    
this.a = 5; 
setTimeout( ()=>{        
    console.log('value of a = ' + this.a );    },0); 
}();
In this case, the “this” keyword, inside the callback function has the same scope as the “this” keyword outside the callback function.

Comments

Popular posts from this blog

Docker Commands

Dockerfile

ES-6 classes