Could someone please give me a brief introduction to lexical this?
\"An arrow function expression (also known as fat arrow function) has a shorter syn
Lets say you have a click listener. In that listener you are performing some AJAX operation like setTimeout
. After the set time has been reached, the code inside the callback will be executed. Inside that callback you may have accessed this
to change the color of the clicked button. But the control will be out of context due to AJAX operation. ES2015 introduced the arrow function to fix that problem. The arrow function captures the this
value of the enclosing context.
The example use-case is:
$('.btn').click(function () {
setTimeout(function () {
$(this).text('new');
// This will cause an error since function() defines this as the global object.
} ,100);
});
To avoid this case:
$('.btn').click(function () { // <- Enclosing context
setTimeout( () => {
$(this).text('new') }
// This works, because this will be set to a value captured from the enclosing context.
,100);
});