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

前端 未结 19 2857
清酒与你
清酒与你 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:58

    First you must visit MDN IIFE , Now some points about this

    • this is Immediately Invoked Function Expression. So when your javascript file invoked from HTML this function called immediately.
    • This prevents accessing variables within the IIFE idiom as well as polluting the global scope.
    0 讨论(0)
  • 2020-11-21 05:00

    Self-invocation (also known as auto-invocation) is when a function executes immediately upon its definition. This is a core pattern and serves as the foundation for many other patterns of JavaScript development.

    I am a great fan :) of it because:

    • It keeps code to a minimum
    • It enforces separation of behavior from presentation
    • It provides a closure which prevents naming conflicts

    Enormously – (Why you should say its good?)

    • It’s about defining and executing a function all at once.
    • You could have that self-executing function return a value and pass the function as a param to another function.
    • It’s good for encapsulation.
    • It’s also good for block scoping.
    • Yeah, you can enclose all your .js files in a self-executing function and can prevent global namespace pollution. ;)

    More here.

    0 讨论(0)
  • 2020-11-21 05:00

    Scope isolation, maybe. So that the variables inside the function declaration don't pollute the outer namespace.

    Of course, on half the JS implementations out there, they will anyway.

    0 讨论(0)
  • 2020-11-21 05:08

    One difference is that the variables that you declare in the function are local, so they go away when you exit the function and they don't conflict with other variables in other or same code.

    0 讨论(0)
  • 2020-11-21 05:09

    Is there a parameter and the "Bunch of code" returns a function?

    var a = function(x) { return function() { document.write(x); } }(something);
    

    Closure. The value of something gets used by the function assigned to a. something could have some varying value (for loop) and every time a has a new function.

    0 讨论(0)
  • 2020-11-21 05:10

    It's all about variable scoping. Variables declared in the self executing function are, by default, only available to code within the self executing function. This allows code to be written without concern of how variables are named in other blocks of JavaScript code.

    For example, as mentioned in a comment by Alexander:

    (function() {
      var foo = 3;
      console.log(foo);
    })();
    
    console.log(foo);

    This will first log 3 and then throw an error on the next console.log because foo is not defined.

    0 讨论(0)
提交回复
热议问题