What is the purpose of wrapping whole Javascript f

2018-12-31 04:42发布

I have been reading a lot of Javascript lately and I have been noticing that the whole file is wrapped like the following in the .js files to be imported.

(function() {
    ... 
    code
    ...
})();

What is the reason for doing this rather than a simple set of constructor functions?

8条回答
孤独寂梦人
2楼-- · 2018-12-31 05:09
  1. To avoid clash with other methods/libraries in the same window,
  2. Avoid Global scope, make it local scope,
  3. To make debugging faster (local scope),
  4. JavaScript has function scope only, so it will help in compilation of codes as well.
查看更多
不再属于我。
3楼-- · 2018-12-31 05:11

That's called a closure. It basically seals the code inside the function so that other libraries don't interfere with it. It's similar to creating a namespace in compiled languages.

Example. Suppose I write:

(function() {

    var x = 2;

    // do stuff with x

})();

Now other libraries cannot access the variable x I created to use in my library.

查看更多
登录 后发表回答