Can I name a JavaScript function and execute it immediately?

前端 未结 8 1735
谎友^
谎友^ 2020-11-28 04:04

I have quite a few of these:

function addEventsAndStuff() {
  // bla bla
}
addEventsAndStuff();

function sendStuffToServer() {
  // send stuff
  // get HTML         


        
8条回答
  •  -上瘾入骨i
    2020-11-28 04:17

    There's nothing wrong with the example you posted in your question.. The other way of doing it may look odd, but:

    var addEventsAndStuff;
    (addEventsAndStuff = function(){
        // add events, and ... stuff
    })();
    

    There are two ways to define a function in JavaScript. A function declaration:

    function foo(){ ... }
    

    and a function expression, which is any way of defining a function other than the above:

    var foo = function(){};
    (function(){})();
    var foo = {bar : function(){}};
    

    ...etc

    function expressions can be named, but their name is not propagated to the containing scope. Meaning this code is valid:

    (function foo(){
       foo(); // recursion for some reason
    }());
    

    but this isn't:

    (function foo(){
        ...
    }());
    foo(); // foo does not exist
    

    So in order to name your function and immediately call it, you need to define a local variable, assign your function to it as an expression, then call it.

提交回复
热议问题