The biggest advantages of using arrow function is that they share the surrounding 'this' keyword.
Arrow function do not have their own 'this' keyword. They simply uses the 'this' they written in .
Lets see an example,
var box ={
color:"green",
position:1,
clickMe:function(){
console.log('inside method of box object '+ this.color+' '+this.position);
document.querySelector(".green").addEventListener('click',function(){
console.log("inside regular function call of event listener");
var str='this is a box with color'+this.color+' which position is'+this.position;
alert(str);
})
}
}
box.clickMe();
We already know that in regular function call 'this' will point to the global object which is window object. But in method call 'this' will point to the object the method call from .
So, in the above example 'this' will point to the box object ,so the color and position of box property will give the proper output, but in the listener callback method is a regular function call so 'this' will point to the global object(window). so color and position will give undefined as output.
So, a simple solution is we can store 'this' to a variable and can use that. let see-
var box ={
color:"green",
position:1,
clickMe:function(){
var self=this; //this is the hack
console.log('inside method of box object '+ this.color+' '+this.position);
document.querySelector(".green").addEventListener('click',function(){
console.log("inside regular function call of event listener");
var str='this is a box with color'+self.color+' which position is'+self.position;
alert(str);
})
}
}
box.clickMe();
Here, we are storing the 'this' of the object so that now we can use it to regular function call to get our desired output.
But we can easily do this by using arrow function in javascript. Because we already know arrow function uses the lexical 'this' keyword.
const box ={
color:"green",
position:1,
clickMe:function(){
console.log('inside method of box object '+ this.color+' '+this.position);
document.querySelector(".green").addEventListener('click',()=>{
console.log("inside regular function call of event listener");
var str='this is a box with color'+this.color+' which position is'+this.position;
alert(str);
})
}
}
box.clickMe();