В 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
До ES6 мы использовали IIFE для создания переменных, которые не будут загрязнять глобальную область, но после ES6 мы обычно используем let
и const
, потому что они предоставляют block-scope .