[英]Whether the nested function hoisting affects the global variable (declared in the same function)?
var b = 4;
function f() {
b = 7;
return b;
}
a = f();
console.log(a); //output: 7
console.log(b); //output: 7
在上面的代码中, b = 7
使 b 自动全局,从而将var b
的值更改为 7。但是当如下添加嵌套的 function b 时,我对 output 结果感到困惑:
var b = 4;
function f() {
b = 7;
return b;
function b() {}
}
a = f();
console.log(a); //output: 7
console.log(b); //output: 4
In my opinion, since function b is hoisting in function f, a reference to function b is first created on the activation object, and when we get the interpreter gets to b = 7
, we already see the property name b exists so the code b = 7
什么都不做并继续,因此console.log(b)
输出4
。 但是为什么console.log(a)
仍然输出7
? b = 7
在这里应该什么都不做,对吧?
对于第一个代码块,这个断言是不准确的:
在上面的代码中,b = 7 使 b 自动成为全局变量,从而将 var b 的值更改为 7。
在语句b = 7
中, b 绑定到外部var b
声明,因此b = 7
分配给闭包中的b
变量。
在第二个代码块中,您对提升的作用存在误解。 将提升视为简单地将声明移动到其 scope 的顶部,因此:
function f() {
b = 7;
return b;
function b() {}
}
...表现得好像你这样做了:
function f() {
let b = function () { }
b = 7;
return b;
}
在行b = 7
上,您将新值7
分配给局部变量b
。 因此return b;
返回 7。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.