gpt4 book ai didi

javascript - 立即调用 IIFE 如何防止它污染全局范围?

转载 作者:行者123 更新时间:2023-11-30 20:25:54 25 4
gpt4 key购买 nike

在关于立即调用函数表达式的 Udacity 类(class)中(关于提供的代码片段)它说:

The function that is being returned closes over (i.e., captures) the hi variable. This allows myFunction to maintain a private, mutable state that cannot be accessed outside the function! What's more: because the function expressed is called immediately, the IIFE wraps up the code nicely so that we don't pollute the global scope.

我正在努力理解立即调用匿名函数与防止变量 hi“污染全局范围”有什么关系,因为 hi 已经在函数中定义,它是否已经在本地/私有(private)范围内?

const myFunction = (
function () {
const hi = 'Hi!';
return function () {
console.log(hi);
}
}
)();

最佳答案

在现代 JavaScript 中,你有 let 和 block 作用域(我很确定 const 也有 block 作用域),所以你可以这样做:

let myFunction;
{
let hi = 'Hi!';
myFunction = function () {
console.log(hi);
};
}

这会创建 myFunction 而不会将 hi 泄漏到周围的作用域中。

在传统的 JavaScript 中,您只有 var 和函数作用域,您可以这样做:

var myFunction;
function a_private_scope() {
var hi = 'Hi!';
myFunction = function () {
console.log(hi);
};
}
a_private_scope();

a_private_scope 限制了 hi 的范围,但是(它是一个函数声明)它需要显式调用,我们仍然向周围的范围泄漏一个名称(这次是 a_private_scope,函数服务范围的名称。

通过使用函数 expression 并立即调用它,我们避免了这个名字污染:

var myFunction;
(function () {
var hi = 'Hi!';
myFunction = function () {
console.log(hi);
};
})();

现在唯一在外部作用域中定义的是 myFunction。作为 hi 作用域的匿名函数没有名称,它可能会污染周围的作用域。

最后我们可以通过使用返回值来清理它,所以我们不必两次提及 myFunction:

var myFunction = function () {
var hi = 'Hi!';
return function () {
console.log(hi);
};
}();

(这也为我们节省了一对 ( ) 因为 function 关键字不再出现在语句的开头。 )

关于javascript - 立即调用 IIFE 如何防止它污染全局范围?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50940766/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com