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

前端 未结 19 2796
清酒与你
清酒与你 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 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.

提交回复
热议问题