Why would one write global code inside a function definition-call pair?

后端 未结 5 1657
轮回少年
轮回少年 2020-12-19 08:27

I see examples where JavaScript code including jQuery and jslint use the notation below:

(function(){
  // do something
})();

instead of:

5条回答
  •  别那么骄傲
    2020-12-19 09:08

    That syntax is to create local scope, as others have commented, but also to make the function self-executing. Note that simply creating local scope could also be accomplished like this:

    var foo = function(){
       // local code
    };
    foo();
    

    But if that's all you're doing, and foo has no other utility beyond calling it one time, then the anonymous, self-executing syntax simply saves you the extra var declaration:

    (function(){
       // local code
    })();
    

    In frameworks that use OOP patterns, this is also the syntax used to create singletons since the function can only run once and can never be called again by external code.

提交回复
热议问题