如果您想在JavaScript中使用某种私有变量,可以将代码放在匿名闭包中,对吗?现在,由于包含了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
答案 0 :(得分:2)
在Javascript中有一个叫做Hoisting的东西,甚至在初始化之前就将其“提升”了。
// 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
在ES6之前,我们曾经使用IIFEs来创建不会污染全局范围的变量,但是在ES6之后,我们通常使用let
和const
,因为它们提供了block-scope