Lexical Scoping Binding Value of this
suggest changeArrow functions are lexically scoped; this means that their this Binding is bound to the context of the surrounding scope. That is to say, whatever this refers to can be preserved by using an arrow function.
Take a look at the following example. The class Cow has a method that allows for it to print out the sound it makes after 1 second.
class Cow {
constructor() {
this.sound = "moo";
}
makeSoundLater() {
setTimeout(() => console.log(this.sound), 1000);
}
}
const betsy = new Cow();
betsy.makeSoundLater();
In the makeSoundLater() method, the this context refers to the current instance of the Cow object, so in the case where I call betsy.makeSoundLater(), the this context refers to betsy.
By using the arrow function, I preserve the this context so that I can make reference to this.sound when it comes time to print it out, which will properly print out “moo”.
A regular function in place of the arrow would not use the class instance as this. Class bodies are strict, so that callback's this is undefined, and this.sound throws TypeError. In a non-strict script it would be the global object instead.