Javascript Odd Scoping Behavior

匆匆过客 提交于 2019-12-02 00:34:39

Two-pass parsing. The code will be treated as if it was

function f() {
   var scope;  // var created, but no value assigned. this overrides the earlier global
   console.log(scope);
   scope = 'local';
   console.log(scope);
}

The var's CREATION will be executed as if it was the very first bit of code executed in the function. But the actual assignment operation won't occur until where it normally would.

Javascript sometimes behaves a bit differently from other languages. Take a look at http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html, they explain it a bit.

If you omit the var statement, the first log uses the global variable, which is set with the string "global". There is no other local variable and no hoisting.

  1. First log: global variable scope set with "global" content
  2. Assignment of new string for the same global variable
  3. Second log: global variable scope set with "local" content
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!