在JavaScript中封装 [英] Encapsulation in JavaScript

查看:98
本文介绍了在JavaScript中封装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很久以前,我看到有人用他们的代码封装了整个JavaScript块,代码类似下面的代码:

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

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

问题:


  1. 上面的代码是否正确?

  2. 如上所述封装整个JavaScript块有什么好处?


推荐答案

是的,这是正确的。它被称为自调用匿名函数表达式。

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

JavaScript变量具有函数范围或全局范围。没有块范围。将代码包含在自调用函数(如示例中的代码)中,可为一次性使用的即时运行代码创建临时本地作用域,而不会污染全局名称空间。

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.

请考虑以下事项:

<html>
<body>
...
<script>
   (function() { 
      var x = '';

      function myFunction () {
         alert('Hello: ' + x);
      }

      x = 'Bob';
      myFunction();

      alert(typeof x);            // string
      alert(typeof myFunction);   // function
   })();

   alert(typeof x);               // undefined
   alert(typeof myFunction);      // undefined
</script>
<script src="other-javascript.js"></script>
</body>
</html>

无论你声明什么,自我调用函数都保存在一个单独的范围内。无法从其他任何地方访问变量 x 和函数 myFunction()。例如, other-javascript.js 中的代码将不会看到它们,并且可以自由地声明另一个函数 myFunction()没有冲突。

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.

这篇关于在JavaScript中封装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆