let*_*nje 2 javascript global-variables
var foo = 'hello';
var myfunc = function() {
console.log(foo);
var foo = foo || 'world';
console.log(foo);
}
myfunc();
Run Code Online (Sandbox Code Playgroud)
为什么第一个foo记录为'undefined'?
因为使用"var"实际声明变量的哪一行是无关紧要的,只要它保持在同一个函数中.如果函数在其中的var x任何位置声明了,则对该名称的任何引用都被视为声明它的作用域的本地.
当然,通常在声明变量之前不引用变量,但请考虑以下代码段:
function foo(a) {
if (a) {
var b = "something";
}
console.log(b);
}
Run Code Online (Sandbox Code Playgroud)
变量b是该函数的本地变量,因此无论其值是什么a,使用b都不会意外地引用在封闭范围上声明的变量.
注意:javascript只有函数级别作用域,它没有块级别作用域.