执行 JavaScript 代码的尴尬方式

在 Google 在 Flask 应用程序中实现 Google + 登录的教程中,我发现开发人员经常使用一种笨拙的方法来执行 JavaScript 代码:

Instead of doing

var a = foo(bar);

我看到了这个:

var a = (function() {
return foo(bar);
})();

为什么要用这种奇怪的方式呢?

2782 次浏览
var a = (function() {
return foo(bar);
})();

In this case this is really unnecessary, but this is not wrong and it will not throw an error.

但是 IIF有时候会像 module pattern一样使用:

var a = (function() {
/* some other code in own scope */
return foo(bar);
})();

在这种情况下,IIF只是一个 module,它向外输出一些东西。

这是一个糟糕的例子,请考虑以下几点:

var a = (function() {
var ret = {};
ret.test = "123";


function imPrivate() { /* ... */ }
ret.public = function() {
imPrivate();
}
return ret;
})();


console.log(a)

a将包含变量 test 和函数 public,但是您不能访问 imPrivate。这是处理公共变量和私有变量的常用方法;

有关更多信息,请参见 为什么这个函数用括号括起来,后面跟着括号?

The closure function is used to encapsulate some of the attributes / methods in the function. Much like the private / public principle from other languages.

你可以找到更多关于这个主题的信息