What is the purpose of a self executing function in javascript?

前端 未结 19 2804
清酒与你
清酒与你 2020-11-21 04:22

In javascript, when would you want to use this:

(function(){
    //Bunch of code...
})();

over this:

//Bunch of code...
         


        
19条回答
  •  梦谈多话
    2020-11-21 04:49

    Simplistic. So very normal looking, its almost comforting:

    var userName = "Sean";
    
    console.log(name());
    
    function name() {
      return userName;
    }
    

    However, what if I include a really handy javascript library to my page that translates advanced characters into their base level representations?

    Wait... what?

    I mean, if someone types in a character with some kind of accent on it, but I only want 'English' characters A-Z in my program? Well... the Spanish 'ñ' and French 'é' characters can be translated into base characters of 'n' and 'e'.

    So someone nice person has written a comprehensive character converter out there that I can include in my site... I include it.

    One problem: it has a function in it called 'name' same as my function.

    This is what's called collision. We've got two functions declared in the same scope with the same name. We want to avoid this.

    So we need to scope our code somehow.

    The only way to scope code in javascript is to wrap it in a function:

    function main() {
      // We are now in our own sound-proofed room and the 
      // character-converter libarary's name() function can exist at the 
      // same time as ours. 
    
      var userName = "Sean";
    
      console.log(name());
    
      function name() {
        return userName;
      }
    }
    

    That might solve our problem. Everything is now enclosed and can only be accessed from within our opening and closing braces.

    We have a function in a function... which is weird to look at, but totally legal.

    Only one problem. Our code doesn't work. Our userName variable is never echoed into the console!

    We can solve this issue by adding a call to our function after our existing code block...

    function main() {
      // We are now in our own sound-proofed room and the 
      // character-converter libarary's name() function can exist at the 
      // same time as ours. 
    
      var userName = "Sean";
    
      console.log(name());
    
      function name() {
        return userName;
      }
    }
    
    main();
    

    Or before!

    main();
    
    function main() {
      // We are now in our own sound-proofed room and the 
      // character-converter libarary's name() function can exist at the 
      // same time as ours. 
    
      var userName = "Sean";
    
      console.log(name());
    
      function name() {
        return userName;
      }
    }
    

    A secondary concern: What are the chances that the name 'main' hasn't been used yet? ...so very, very slim.

    We need MORE scoping. And some way to automatically execute our main() function.

    Now we come to auto-execution functions (or self-executing, self-running, whatever).

    ((){})();
    

    The syntax is awkward as sin. However, it works.

    When you wrap a function definition in parentheses, and include a parameter list (another set or parentheses!) it acts as a function call.

    So lets look at our code again, with some self-executing syntax:

    (function main() {
      var userName = "Sean";
    
        console.log(name());
    
        function name() {
          return userName;
        }
      }
    )();
    

    So, in most tutorials you read, you will now be bombard with the term 'anonymous self-executing' or something similar.

    After many years of professional development, I strongly urge you to name every function you write for debugging purposes.

    When something goes wrong (and it will), you will be checking the backtrace in your browser. It is always easier to narrow your code issues when the entries in the stack trace have names!

    Hugely long-winded and I hope it helps!

提交回复
热议问题