2014-09-02 55 views
0

在javascript變量聲明中被懸掛在頂部。關閉中變量的提升

var v; 
v=1;     ---------------------------- 
var getValue=(function(v){ 
return function(){return v;}; 
})(v); 
v=2;    -----------------------------VVV 

            both are outside function 

but results getValue();//1 

爲什麼這個時候v=2不是在頂部懸掛?

回答

1

你看到12是不是提升的原因,而是你創造與IIFE周圍getValueclosure - 在本地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