Saturday, February 11, 2017

ES6 Arrow Functions - 'this'


‘this’ - Determines when you must use an arrow function
A normal anonymous function identifies the calling element as ’this’
But an arrow function inherits ‘this’ from its parent.

element.addEventListener(‘click’, function(){
  console.log(this);//‘this’ is element here
  setTimeout(function(){
    console.log(this) //‘this’ is ‘window’ here because the current function we are in is not bound to
    //any scope 
    //(unlike the previous function which was bound to element’s click event).
    },200);
}); 

Solution, use arrow function inside setTimeout.

element.addEventListener(‘click’, function(){
  console.log(this);//‘this’ is element here
  setTimeout(()=>{
    console.log(this) //‘this’ is still ‘element’ here because the current function we are in inherits ‘this’ 
    //from its parent 
    //our arrow function is bound to ‘element’, making ‘this’ equal to element.
},200);
}); 

If we are calling an unbounded function statement inside a bounded scope of a parent function, it goes out into global scope. We can use arrow function to preserve the value of ‘this’ instead of jumping out in the unbounded global scope.

element.classList.contains(‘classname’); //contains can be used to check for a class

*Functions that are not bound to any element, like setTimeout, have 'this' set to window.
*Arrow functions inherit 'this' from their lexical parent 



No comments:

Post a Comment