gpt4 book ai didi

javascript - 让 let 替换匿名闭包以获得私有(private)变量吗?

转载 作者:行者123 更新时间:2023-11-29 20:40:42 24 4
gpt4 key购买 nike

如果您想在 JavaScript 中使用某种私有(private)变量,您可以将代码放在匿名闭包中,对吗?现在既然包含了 let,闭包的这个特定用例就消失了吗?或者它仍然相关吗?

顶级示例:

// global variable a
var a = 6;

// using let
{
// new variable a that only lives inside this block
let a = 5;
console.log(a); // => 5
}

console.log(a); // => 6

// using a closure
(function() {
// again a new variable a that only lives in this closure
var a = 3;
console.log(a); // => 3
})();

console.log(a); // => 6

最佳答案

有一种东西叫Hoisting在 Javascript 中,它甚至在初始化之前就“提升”了上面的变量。

// global variable a
var a = 6;

// using let
{
// new variable a that only lives inside this block
let a = 5;
console.log(a); // => 5
}

console.log(a); // => 6

// using a closure
(function() {
// again a new variable a that only lives in this closure
var a = 3;
console.log(a); // => 3
})();

console.log(a); // => 6

所以这段代码变为:

// The global variable 'a' is hoisted on the top of current scope which is Window as of now
var a;

// Initialization takes place as usual
a = 6;


// This is a block
{

// This local variable 'a' is hoisted on the top of the current scope which is the 'block'
let a;

a = 5;
console.log(a); // => 5
}

console.log(a); // => 6

// Using an IIFE
(function() {

// This local variable 'a' is hoisted on the top of the current scope which is the block of IIFE
var a;

a = 3;
console.log(a); // => 3
})();

console.log(a); // => 6

我们曾经使用 Pre ES6 IIFEs使变量不会污染全局范围,但在 ES6 之后我们通常使用 letconst 因为它们提供了 block-scope .

关于javascript - 让 let 替换匿名闭包以获得私有(private)变量吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55650547/

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