繁体   English   中英

嵌套的 function 吊装是否影响全局变量(在同一函数中声明)?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM