Arrow 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".
If you had used a regular function in place of the arrow function, you would lose the context of being within the class, and not be able to directly access the sound
property.