Why do I have to omit parentheses when passing a function as an argument?

前端 未结 2 1058
醉梦人生
醉梦人生 2020-12-15 12:44

I am trying to wrap my head around as to why the following code results in a stack overflow when the parentheses are included, but do not when they omitted.

I am ca

相关标签:
2条回答
  • 2020-12-15 13:09

    This question is usually first asked in reference to setTimeout, but I think it's important to point out that the behavior here isn't specific to that function. You simply need to understand what the parenthesis do and what it means to leave them off.

    Assume the following function:

    function foo() {
        return 5;
    }
    

    Consider the following two variable declarations/assignments:

    var one = foo();
    var two = foo;
    

    What values do these variables have?

    In the first case we're executing the foo function and assigning its return value -- the number 5 -- to one. In the second case we're assigning foo itself -- more precisely, a reference to foo -- to two. The function is never executed.

    With this knowledge and an understanding that setTimeout expects as its first argument a reference to a function, it should be obvious why your first case fails, but the second one works.

    Of course, your problem is exacerbated by the fact that the function you're executing is a recursive call to itself. This will just run forever -- for some definition of forever -- because there's no base case to terminate the recursion.

    0 讨论(0)
  • 2020-12-15 13:10

    By writing

    foo()
    

    you're actually calling foo at that moment. Which of course then calls foo() again...until you stackoverflow.

    In case 2 you're effectively passing a "reference" to foo, saying "run this in 2s". Not actually calling foo().

    So use parens when you actually want to invoke it. Not when you want to refer to it.

    0 讨论(0)
提交回复
热议问题