gpt4 book ai didi

javascript - 嵌套函数提升是否影响全局变量(在同一函数中声明)?

转载 作者:行者123 更新时间:2023-11-30 09:11:46 26 4
gpt4 key购买 nike

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 绑定(bind)到外部 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; 返回 7。

关于javascript - 嵌套函数提升是否影响全局变量(在同一函数中声明)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58193542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com