Capture this with an Arrow Function

Share this video with your friends

Send Tweet

Arrow functions are not only syntactically different from other JavaScript functions, but they also have special this behavior. An arrow function doesn't have its own this. Instead, it uses the this value from its enclosing execution context.

When an arrow function is created, it permanently captures the surrounding this value. Neither call() nor apply() can change the this value later. Additionally, arrow functions cannot be used as constructors.

This lesson demonstrates that arrow functions are this-transparent and illustrates how they can solve the problem of incorrect this values within callback functions.

Rihan
Rihan
~ 6 years ago

Since, setInterval takes an handler as its parameter, we can write it without arrow function as below

const counter = {
  count: 0,
  incrementPeriodically() {
    setInterval((function() {
      console.log(++this.count);
    }).bind(counter), 1000)
  }
}
felikf
felikf
~ 5 years ago

It would be worth it to mention this issue I ran recently into: https://stackoverflow.com/questions/31095710/methods-in-es6-objects-using-arrow-functions