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