如果变量存在于不执行的if语句中,则变量会被初始化/存储在内存中,如下所示:
function blah(){
if(something === true){
var blahOne = 1;
var blahTwo = 2;
var blahThree = 3;
} else {
console.log('The above if statement usually won\'t execute');
}
}
我的假设是否定的,但Javascript至少可以说是一种古怪的语言。在此先感谢您的帮助!
答案 0 :(得分:4)
所有var
声明都移到函数顶部并初始化为undefined。这称为可变吊装。 JavaScript没有块范围,只有函数和全局范围。
您的代码等同于以下
function blah(){
var blahOne, blahTwo, blahTree;
if(something === true){
blahOne = 1;
blahTwo = 2;
blahThree = 3;
} else {
// blahOne, blahTwo, blahThree are set to undefined
console.log('The above if statement usually won\'t execute');
// But since they have been declared, there's no error in reading them
console.log(blahOne, blahTwo, blahThree);
}
}
答案 1 :(得分:1)
Javascript中没有像block scope
这样的东西。见article。如果你想这样说:Javascript有功能范围。所以问题的答案是yes
它们被初始化了。