2

I stumbled on this code in react.js tutorial

   componentDidMount() {
     this.timerID = setInterval(() => this.tick(),1000);
   }

(This componentDidMount() is inside React.Component extension class)

The question is, why I need to bind with () => first?

while if outside class I can just do

setInterval(tick,1000)

EDIT: in my defense of mark as duplicate question, the provided link of the duplicate question revolves around 'this' keyword. While what I really asked is why should I use arrow function / binding inside the class. Although the answer point to how to use 'this' keyword, the origin and the question is absolutely unique.

alvseek
  • 191
  • 2
  • 10
  • In the tutorial, `tick` is a method within the class. Since it's an **arrow function** (inside the checkInterval), the contextual `this` **is the class one (Clock), NOT the interval function's scope**, hence you're accessing the tick method of the class itself. Outside of the class, you're calling **another** tick method, which is the one declared at the beginning of the tutorial. http://prntscr.com/l7vv49 – briosheje Oct 19 '18 at 10:05
  • A related question: [I'm having a lot of trouble with setInterval and class methods](https://stackoverflow.com/questions/52847856/im-having-a-lot-of-trouble-with-setinterval-and-class-methods/52847962#52847962) – undefined Oct 19 '18 at 10:14

1 Answers1

1

() => is arrow function and the value of this inside an arrow function is determined by the surrounding scope. Without the arrow function this inside setInterval will get a new scope so this.tick will not work. if you are using the arrow function the scope of this will be same for both outside & inside of the setInterval

brk
  • 43,022
  • 4
  • 37
  • 61