Javascript function call with/without parentheses

后端 未结 6 1774
南旧
南旧 2021-02-11 07:39

code_0:

(calling foo without parentheses)

function foo(){
    console.log(\'hello world\');
}

setTimeout(foo, 2000);

This

6条回答
  •  心在旅途
    2021-02-11 08:07

    The point of confusion here is that you're not realizing that using foo without parentheses is not calling the function...it's only referencing it.

    foo is the reference to the function itself. To call a function (i.e. actually execute its code) you reference it with parentheses at the end (e.g. foo()). In a practical sense that means:

    // references the function itself
    // ...you could call one() now and it would run the function foo
    var one = foo;
    
    // runs/calls the function, and var two will then be whatever foo returns
    var two = foo();
    

    So in the first example you are NOT calling the function. You are passing the function foo to setTimeout. setTimeout will then call it after a delay.

    In the second example you called foo immediately and passed whatever foo returns to setTimeout (which setTimeout couldn't do anything with, because that return value likely wasn't another function). So your function was executed immediately and then nothing would have happened (except likely some errors) after setTimeout was done with its delay.

提交回复
热议问题