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


I am trying to wrap my head around, because when adding brackets, the following code in a stack overflow Why the results get, but when they are not omitted

I am calling the function as an argument for setTimeout and it works without a footnote, but when I add them fixed The form fails. It was my intuition to add () after the ceremony, just hope someone can clean it for me when the parance is optional and not?

Case 1:

  var a = 1; Function foo () {a ++; Document.write (a); SetTimeout (foo (), 2000)} a ???? // RangeError: Max call stack size exceeded   

Case 2:

  var a = 1; Function foo () {a ++; Document.write (a); SetTimeout (foo, 2000)} a ???? // feet are left on the fu function and it works.     

This question usually refers to the setTimeout I am asked first, but I think it is important to say that the behavior here is not specific to that celebration. You need to understand what the bracket has to do and what it means to quit.

Assume the following functions:

  function foo () {return 5; }   

Consider the following two variable declarations / assignments:

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

What are the values ​​of these variables?

In the first case we have performed to foo function and assign its return value - number 5 - the a . In the second case we are specifying foo - more accurate, the function is never executed with respect to foo - two is.

With this knowledge and understanding that setTimeout expects context as its first argument for a function, it should be clear why Your first case fails, but the second works.

Of course, the problem is more than the fact that the action you are performing is called recursive themselves forever - always run for a definition - because recycling to end There is no basis case.

Comments