While studying, React found the following code:

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

Why is this.tick() standing before this.tick() () ? If I understand correctly this is the kind of anonymous function declaration? But after all setInterval requires a function in the first place and tick() is a method of this class, that is, it is a function.

    1 answer 1

    Arrow functions

    The expressions of the switch functions have a shorter syntax compared to functional expressions and are lexically bound to the value of this (but not attached to its own this , arguments , super , or new.target ).
    Arrow functions are always anonymous.

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

    almost equivalent

     let that = this; this.timerID = setInterval( function () { return that.tick();}, 1000 ); 

    Why do I need to declare an anonymous function to call another function?

    So shorter, more convenient and clearer.
    Another valid option would be setTimeout(this.tick.bind(this), 1000) , otherwise an object on this will not be available inside tick. This is an object method, not just a function.

    • Thank you, but the question is slightly different. Why do I need to declare an anonymous function to call another function? - Telion
    • So shorter and more convenient and clearer. Another valid option would be setTimeout(this.tick.bind(this), 1000) , otherwise an object on this will not be available inside tick. This is an object method, not just a function. - vp_arth