var name = 'world';
(function () {
if (typeof name === 'undefined') {
console.log('Goodbye ' + name);
} else {
console.log('Hello ' + name);
}
})();
当我评估上面的程序时,结果是Hello world!
,这是因为全局变量范围,但是当我评估以下程序时:
var name = 'world';
(function () {
if (typeof name === 'undefined') {
var name = 'Jack';
console.log('Goodbye ' + name);
} else {
console.log('Hello ' + name);
}
})();
结果为Goodbye Jack
,为什么typeof name === 'undefined'
的结果在这种情况下为true
?
答案 0 :(得分:1)
因为变量声明被提升到它们出现的范围的顶部。这就是你的代码的解释方式:
(function () {
var name; // Implicitly has the value 'undefined'
if (typeof name === 'undefined') {
name = 'Jack'; // Doesn't change from 'undefined' until this line
console.log('Goodbye ' + name);
} else {
console.log('Hello' + name);
}
})();
答案 1 :(得分:0)
在第3行,您有var name = 'Jack'
。
提升var name
部分,因此您有一个作用于该函数的局部变量。
name = 'Jack'
部分未被吊起。
在第2行,您测试name
的值。
第2行在第3行之前,因此尚未分配'Jack'
,因此它是undefined
。
答案 2 :(得分:0)
在Javascript function
声明中(例如function f() {}
),var
声明已“悬挂”。
它们是为函数的范围声明的(尽管将变量设置为Jack
仍然是你写的那个)。