when to use function() , function or () => function(callback)

后端 未结 3 1765
渐次进展
渐次进展 2021-01-21 08:12

I have been searching for a while for a good explanation so its all clear to me. Example:

this.onDeleteHandler(index)}/>
3条回答
  •  伪装坚强ぢ
    2021-01-21 08:33

    The whole question seems to boil down to what the difference between func and func() and () => func() is. It has nothing to do specifically with React.

    If I have a function

    function func() {
      console.log(42);
    }
    

    Then I can reference the function object itself via func. This is useful if I need to pass the function to another function, e.g. setTimeout:

    setTimeout(func, 1000); // calls func after 1000ms
    

    setTimeout expects a function that it can call after the provided timeout.

    Similarly in React, click, change etc are all props that expect to be passed a function that is called when the event happens.


    func() on the other hand calls the function. This needs to be done if you actually need to call function right then and there. This implies that if I do

    setTimeout(func(), 1000);
    

    then I would call func first and pass its return value to setTimeout (i.e. I call func now, setTimeout doesn't call it later). So this is usually incorrect unless func returns a function itself and its really the return value I want to pass to the other function.


    () => func() is just a new function that only calls func. For all intends and purposes it is equivalent to func:

    function func() {
      console.log(42);
    }
    
    const anotherFunc = () => func();
    
    func();
    anotherFunc();

    And of course if func expects an argument then I have to pass it along when wrapping it in another function, which is what x => func(x) does.


    The other part is how functions assigned to object properties and this work. In short, what this refers to inside a (non-arrow) function depends on how the function is called. Doing

    this.foo();
    // or
    var bar = this.foo;
    bar();
    

    produces two different results because this.foo() and bar() are two different ways to call the function. For more info see How to access the correct `this` inside a callback?

提交回复
热议问题