繁体   English   中英

需要帮助来了解关闭

[英]Need help understanding closures

我当时正在了解闭包,并尝试做一些实验,那时我遇到了这个问题。

当我执行以下代码时:

  var hello; hello = 'abc'; test(); function test() { console.log(hello); } 

输出:“ abc”

现在,如果我在函数内添加另一个变量声明,则输出将不同

  var hello; hello = 'abc'; test(); function test() { console.log(hello); var hello = 'xyz'; } 

输出:未定义

我无法找出为什么它会以这种方式运行。 当执行test()函数时,它会记录变量'hello'直到现在未执行test()函数中的变量声明,因此应为我提供全局hello变量val,但它返回未定义的值。

谢谢你的协助。

这是因为函数测试中的变量hello已提升 ,这意味着:

function test() {
   console.log(hello);
   var hello = 'xyz';
}

实际上与:

function test() {
   var hello;
   console.log(hello);
   hello = 'xyz';
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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