你看到1
不2
是不是提升的原因,而是你创造与IIFE周围getValue
的closure - 在本地v
变量与价值1
阴影全局v
变量。
var v; // hoisted declaration - global variable "v"
v=1; // "1" is assigned to the global
var getValue=(function(v) { // a function with a local "v" variable (parameter)
return function(){return v;}; // access the local "v" variable
})(v); // passing the value of the global variable - "1" as the time of the call
v=2; // "2" is assigned to the global variable
getValue(); // the local variable still has the value: 1
如果省略该参数,您getValue
将返回全局变量 - 作为呼叫的时间吧:
var v; // hoisted declaration
// v=1; // irrelevant
var getValue = // (function() { can be omitted
function() { return v; } // access the global variable
// })()
v = 2; // assign the variable
getValue() // and access it from the closure: 2