如何立即调用IIFE防止其污染全球范围? [英] How does an IIFE's being called immediately prevent it from polluting global scope?
问题描述
在关于立即调用的函数表达式的Udacity课程中(关于提供的代码片段),它说:
In a Udacity lesson on immediately invoked function expressions (regarding the provided code snippet) it says:
正在返回的函数结束(即捕获)
hi变量。这允许myFunction维护一个私有的,可变的
状态,该状态无法在函数外部访问!更重要的是:
因为表达的函数被立即调用,IIFE很好地将
包含在代码中,这样我们就不会污染全局范围。
我很难理解调用匿名函数会立即做什么来阻止变量 hi
从污染全球范围开始,由于 hi
已在函数中定义,是不是已经在本地/私有范围内了?
I'm strugggling to understand what calling the anonymous function immediately has to do with prevent the variable hi
from "polluting the global scope," and since hi
is already defined in a function, isn't it already in local/private scope?
const myFunction = (
function () {
const hi = 'Hi!';
return function () {
console.log(hi);
}
}
)();
推荐答案
在现代JavaScript中,你有让
并阻止范围(我非常确定 const
也有块范围),所以你可以这样做:
In modern JavaScript, you have let
and block scope (and I'm pretty sure const
has block scope, too), so you could just do this:
let myFunction;
{
let hi = 'Hi!';
myFunction = function () {
console.log(hi);
};
}
这会创建 myFunction
没有将 hi
泄漏到周围的范围内。
This creates myFunction
without leaking hi
into the surrounding scope.
在传统的JavaScript中,只有 var
和函数范围,你可以这样做:
In traditional JavaScript, where you only have var
and function scope, you could do this:
var myFunction;
function a_private_scope() {
var hi = 'Hi!';
myFunction = function () {
console.log(hi);
};
}
a_private_scope();
a_private_scope
限制<$ c的范围$ c> hi ,但是(它是一个函数声明)需要显式调用它,我们仍然会向周围的范围泄漏一个名称(这次它是 a_private_scope
,作为范围的函数的名称。。
a_private_scope
limits the scope of hi
, but (it being a function declaration) it needs to be called explicitly, and we still leak a name to the surrounding scope (this time it's a_private_scope
, the name of the function-serving-as-a-scope).
通过使用函数表达式并立即呼吁它,我们避免这个名字污染:
By using a function expression and immediately calling it, we avoid this second name pollution:
var myFunction;
(function () {
var hi = 'Hi!';
myFunction = function () {
console.log(hi);
};
})();
现在外部范围内唯一定义的是 myFunction
。用作 hi
范围的匿名函数没有名称可能会污染周围的范围。
Now the only thing defined in the outer scope is myFunction
. The anonymous function that serves as a scope for hi
has no name it could pollute the surrounding scope with.
最后我们可以通过使用返回值来清理它,所以我们不必提及 myFunction
两次:
Finally we can clean it up a bit by using return values, so we don't have to mention myFunction
twice:
var myFunction = function () {
var hi = 'Hi!';
return function () {
console.log(hi);
};
}();
(这也为我们节省了一对(
)
因为函数
关键字不再出现在语句的开头。)
(This also saves us a pair of (
)
because the function
keyword doesn't appear at the beginning of a statement anymore.)
这篇关于如何立即调用IIFE防止其污染全球范围?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!