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

后端 未结 5 1666
轮回少年
轮回少年 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 08:47

    The main purpose of this (Crockford's) pattern (there are others -- in some cases more performant -- too) is to avoid the pollution of the global scope with named functions/identifiers. By doing stuff within this anonymous closure, you can write your code as you'd do inside the global scope, except that everything declared inside remains local and thus cannot be accessed/referenced from outside. Use-cases where no local variables/functions are used or "exported" (assigned to a named identifier from one of the outer scopes), might exist, but don't necessarily have to be nested within a anonymous funciton.

提交回复
热议问题