0

I have the following React code:

class WarClock extends React.Component{
constructor(props)
{
    super(props)
    this.state={
        dateNow:new Date(),
        name:'yakuza'
    }
}
componentDidMount(){
    this.IntervalID=setInterval(() => this.tick(),1000)
}
componentWillUnmount(){
    clearInterval(this.IntervalID);
}
tick(){ 
    console.log(this);
    this.setState({dateNow:new Date()})
} 
...

If I use this.IntervalID=setInterval(() => this.tick(),1000), the console.log in tick() prints my class object the this component works normally. However, when I use this.IntervalID=setInterval(this.tick,1000), the console.log in tick() prints out the entire 'window' object. As a result, setState() hereby is not found. Can someone explain why when I use tick function pointer as callback, this is binded with the window object? Isn't my tick() a class function of WarClock? Also, why arrow function will resolve this issue, thanks.

VD26
  • 138
  • 2
  • 12
  • When you pass `this.tick` as a standalone expression, you're passing the `tick` function without its calling context (the `this`) – CertainPerformance Nov 09 '19 at 05:48
  • so you mean `() => this.tick()` will pass the function with its context. How do we define a standalone expression? – VD26 Nov 09 '19 at 05:50
  • Eg with `const fn = this.tick`, `fn()` gets invoked with no calling context. Same thing is happening when you pass a callback like that: `(this.tick, otherArg)` gets seen as `(fn, otherArgName)` eventually calling `fn()` without a calling context – CertainPerformance Nov 09 '19 at 05:52
  • Ok, so basically whenever you pass in a function pointer by itself it will become a const, and in order to pass its context you have to wrap it in another function like the arrow one or `(function (){ tick(); })`? – VD26 Nov 09 '19 at 05:58

0 Answers0