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

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

    Self executing function are used to manage the scope of a Variable.

    The scope of a variable is the region of your program in which it is defined.

    A global variable has global scope; it is defined everywhere in your JavaScript code and can be accessed from anywhere within the script, even in your functions. On the other hand, variables declared within a function are defined only within the body of the function. They are local variables, have local scope and can only be accessed within that function. Function parameters also count as local variables and are defined only within the body of the function.

    As shown below, you can access the globalvariable variable inside your function and also note that within the body of a function, a local variable takes precedence over a global variable with the same name.

    var globalvar = "globalvar"; // this var can be accessed anywhere within the script
    
    function scope() {
        alert(globalvar);
        localvar = "localvar" //can only be accessed within the function scope
    }
    
    scope(); 
    

    So basically a self executing function allows code to be written without concern of how variables are named in other blocks of javascript code.

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