var tmp = new Date();
function f() {
console.log(tmp);
if (false) {
var tmp = "hello world";
}
}
f(); // undefined
var tmp = new Date();
function f() {
console.log(tmp);
if (false) {
var tmp = "hello world";
}
}
f(); // undefined
因为if没有块级作用域,因此在if中的var tmp变量提升,实质上你写的代码被转换成这样的:
var tmp = new Date();
function f() {
var tmp;
console.log(tmp);
if (false) {
tmp = "hello world";
}
}
f(); // undefined
tmp没有被赋值,因此是undefined