简体   繁体   English

为什么JavaScript在第二种情况下不查找全局范围

[英]Why javascript doesn't look up global scope in second case

foo will lookup b value with 2 as expected when executing in console 在控制台中执行时,foo将按预期值查找b值为2

function foo() {
    console.log(b)
}
var b = 2
foo() // 2 for console.log

but when I do this 但是当我这样做时

function foo() {
    console.log(b)
    var b = 2
    console.log(b)
}
var b = 2
foo() // undefined for first console.log

it won't lookup b in global scope anymore why ? 它不再在全球范围内查找b为什么?

It is because of what is called Javascript Hoisting, this is how javascript sees your code: 这是因为所谓的Javascript提升,这是javascript看到您的代码的方式:

function foo() {
  var b; // javascript hoisted this variable on top
  console.log(b) // so here you see underfined
  b = 2;
  console.log(b);
}

Now because javascript hoised variable b on top of function, your global variable b was never used and hence statement immendiately after hoisted variable showed undefined . 现在,因为JavaScript hoised变量b上的功能之上,你的全局变量b ,将不再使用,因此声明immendiately升起后可变显示undefined So if you remove new declaration ( var keyword) from your function, you should still have access to global b variable. 因此,如果您从函数中删除新的声明( var关键字),则仍应可以访问全局b变量。

BTW, it is good practice to declare all your variables on top of function like: 顺便说一句,在函数顶部声明所有变量是一个好习惯,例如:

function foo() {
  var b = 2;
  console.log(b);
}

To know more on the topic, see this: 要了解有关该主题的更多信息,请参见:

暂无
暂无

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

相关问题 全局JavaScript变量范围:为什么这不起作用? - Global JavaScript Variable Scope: Why doesn't this work? 为什么全局变量似乎不受内部作用域(Javascript)的影响? - Why global variable doesn't seem to be affected by inner scope (Javascript)? Javascript:为什么全局作用域中的变量成为其“ this”的属性,但在新对象的功能范围内的变量中未发生 - Javascript: Why variable in global scope becomes property of its 'this' but it doesn't happen on variable inside functional scope for new object 为什么局部作用域不引用全局变量? - Why a local scope doesn't refer on a global variable? Javascript:为什么 setCustomValidaty 在第一次提交时不显示,但在第二次提交时显示? - Javascript: why setCustomValidaty doesn't show up on first submission but it does on the second? 为什么在这种情况下无法访问全局scope? - Why global scope can not be accessed in this case? 为什么我的函数没有Javascript变量的范围? - Why Doesn't My Function Have Scope Of The Javascript Variables? 全局范围 createReadStream 不适用于回调 - global scope createReadStream doesn't work for callback 为什么for循环内的全局变量不会改变值? Javascript - Why global variable inside for loop doesn't change value? Javascript JavaScript表单验证:为什么第一种有效,但第二种无效? - JavaScript form validation: Why does the first work but the second doesn't?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM