嵌套函数提升是否影响全局变量(在同一个函数中声明)?
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。但是当如下添加嵌套函数 b 时,我对输出感到困惑结果:
var b = 4;
function f() {
b = 7;
return b;
function b() {}
}
a = f();
console.log(a); //output: 7
console.log(b); //output: 4
在我看来,由于函数 b 在函数 f 中提升,因此首先在激活对象上创建对函数 b 的引用,当我们让解释器到达 b = 7
时,我们已经看到 属性 名称 b 存在,因此代码 b = 7
不执行任何操作并继续进行,因此 console.log(b)
输出 4
。但是为什么console.log(a)
仍然输出7
呢? b = 7
这里应该什么都不做吧?
对于第一个代码块,此断言不准确:
In the codes above, b = 7 makes b automatically global, thus changing the value of var b to 7.
在语句 b = 7
中,b 绑定到外部 var b
声明,因此 b = 7
将 赋值给 b
闭包中的变量。
在第二段代码中,您对提升的作用有误解。将提升视为简单地将声明移动到其范围的顶部,因此:
function f() {
b = 7;
return b;
function b() {}
}
...就像您这样做一样:
function f() {
let b = function () { }
b = 7;
return b;
}
在行 b = 7
上,您正在 分配 一个新值 7
给局部变量 b
。因此 return b;
returns 7.
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。但是当如下添加嵌套函数 b 时,我对输出感到困惑结果:
var b = 4;
function f() {
b = 7;
return b;
function b() {}
}
a = f();
console.log(a); //output: 7
console.log(b); //output: 4
在我看来,由于函数 b 在函数 f 中提升,因此首先在激活对象上创建对函数 b 的引用,当我们让解释器到达 b = 7
时,我们已经看到 属性 名称 b 存在,因此代码 b = 7
不执行任何操作并继续进行,因此 console.log(b)
输出 4
。但是为什么console.log(a)
仍然输出7
呢? b = 7
这里应该什么都不做吧?
对于第一个代码块,此断言不准确:
In the codes above, b = 7 makes b automatically global, thus changing the value of var b to 7.
在语句 b = 7
中,b 绑定到外部 var b
声明,因此 b = 7
将 赋值给 b
闭包中的变量。
在第二段代码中,您对提升的作用有误解。将提升视为简单地将声明移动到其范围的顶部,因此:
function f() {
b = 7;
return b;
function b() {}
}
...就像您这样做一样:
function f() {
let b = function () { }
b = 7;
return b;
}
在行 b = 7
上,您正在 分配 一个新值 7
给局部变量 b
。因此 return b;
returns 7.