Encapsulation in JavaScript

前端 未结 3 1444
傲寒
傲寒 2020-12-02 08:04

A long time ago, I saw someone encapsulate their entire JavaScript block with code something like the code below:

(function() {
  // ...
})(this);

3条回答
  •  执念已碎
    2020-12-02 08:39

    Yes, that's correct. It's called a self invoking anonymous function expression.

    JavaScript variables have either function scope, or global scope. There is no block scope. Enclosing your code in a self invoking function like the one in your example creates a temporary local scope for single-use, immediately-run code, without polluting the global namespace.

    Consider the following:

    
    
    ...
    
    
    
    
    

    Whatever you declare in that self invoking function is held in a separate scope. The variable x and the function myFunction() cannot be accessed from anywhere else. The code in other-javascript.js won't see them, for example, and it would be free to declare another function myFunction() without conflicts.

提交回复
热议问题