Using local variables makes sense in the scenario mentioned above. However, utilizing arrow functions with lexical scope has a broader range of applications.
In today's development landscape, frameworks are commonly used for projects which include components. Variables exist at the component level and are then linked to the HTML elements.
class component {
constructor() {
this.data = {};
}
// For instance, if you retrieve data and need to assign it to this.data
getData() {
somePromise.then((res) => {
this.data = res // you can access the parent object without any issues
})
}
}
On the other hand, when dealing with normal functions:
getData() {
const self = this; // save the parent reference to a local variable
somePromise.then(function(res) {
self.data = res // now you can set the data as the function's 'this' is different here
})
}
There are alternative approaches as well. You can bind an anonymous function with 'this' using the native bind function, allowing you to access the correct context within the function.
Therefore, in practical terms, arrow functions have effectively resolved this dilemma.