2014-09-02 79 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