Difference between calling function and referencing function?

前端 未结 3 1786
爱一瞬间的悲伤
爱一瞬间的悲伤 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:14

    In this case, you are registering a callback function for the window onload event. To do so, you give a reference to the function, you don't execute the function (unless, of course, executing the function returns another function which is used as the callback handler). The function you specify will be executed when the onload event occurs, that is, when the page finishes loading.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 06:39

    You're not calling the function, you're telling the browser which function to call, onload.

    Referencing a function and calling a function are never interchangeable: they're completely different things.

    You may, however, call a function that returns a function:

    function getFunction() {
        return function() {
            alert("I'm the real onload function.");
        };
    }
    
    window.onload = getFunction();
    
    0 讨论(0)
提交回复
热议问题