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

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

    (function(){
        var foo = {
            name: 'bob'
        };
        console.log(foo.name); // bob
    })();
    console.log(foo.name); // Reference error
    

    Actually, the above function will be treated as function expression without a name.

    The main purpose of wrapping a function with close and open parenthesis is to avoid polluting the global space.

    The variables and functions inside the function expression became private (i.e) they will not be available outside of the function.

提交回复
热议问题