Javascript中的变量范围(提升)

前端之家收集整理的这篇文章主要介绍了Javascript中的变量范围(提升)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我的一个朋友正在进行在线测验,他问我这个我无法回答的问题.
  1. var global = false;
  2.  
  3. function test() {
  4. global = true;
  5. return false;
  6. function global() {}
  7. }
  8.  
  9. console.log(global); // says false (As expected)
  10. test();
  11. console.log(global); // says false (Unexpected: should be true)

如果我们假设函数在顶部和var变量一起被提升,让我们试试这个.

  1. var foo = 1;
  2. function bar() {
  3. return foo;
  4. foo = 10;
  5. function foo() {}
  6. var foo = 11;
  7. }
  8.  
  9. bar();
  10. console.log(foo); //says 1 (But should be 11) Why 1 this time ??

这是一个JSBin DemoJSBIN Demo2玩.

PS:如果我们从test()中删除函数global(){},那么它运行正常.有人可以帮我理解为什么会这样吗?

解决方法

var语句和函数声明语句被“提升”到其封闭范围的顶部.
因此,函数中的函数global(){}会创建一个本地全局名称.

分配给函数中的全局内容将绑定到此本地名称.以下是如何使用提升来“重写”它以了解编译器如何看待它:

  1. function test() {
  2. var global = function() {}; // hoisted; 'global' now local
  3. global = true;
  4. return false;
  5. }

猜你在找的JavaScript相关文章