Javascript 闭包中变量的提升

Javascript 闭包中变量的提升,javascript,Javascript,在javascript中,变量声明悬挂在顶部 但是 为什么这次v=2没有被提升到顶部?您看到1not2的原因不是提升,而是围绕getValue创建的,其中带有1值的局部v变量隐藏了全局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" varia

在javascript中,变量声明悬挂在顶部

但是


为什么这次
v=2
没有被提升到顶部?

您看到
1
not
2
的原因不是提升,而是围绕
getValue
创建的,其中带有
1
值的局部
v
变量隐藏了全局
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
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