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

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

提交回复
热议问题