Difference between calling function and referencing function?

前端 未结 3 1816
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-07 05:57

Look at the following code:

window.onload = someFunction;

Many times I see the use of this kind of code and even I use the same. But, there

3条回答
  •  误落风尘
    2020-12-07 06:26

    In JavaScript, parentheses do matter. In your case, you are assigning the function object itself to a certain slot of window. When putting the parentheses, you explicitly call the function, thus the value of someFunction() is the returned value of the function, not the function object itself. In short :

    • when you see a function without parentheses, you are facing an expression which has the value of the function object itself
    • when you see a function with parentheses, the expression has he value of he returned value of the function, because the parentheses indicate a call of the function

    A special case is someVar = new someConstructor; which should not be used generally, and does not follow my short explanation above. For a very good explanation of function, and that particular statement above, see the wonderful book by Douglas Crockford Javascript, the Good Parts.

提交回复
热议问题