JavaScript的if中的函数声明提升在不同浏览器中的表现

下面这段代码在不同浏览器中有不同的表现,ES2015中说在if中的的函数声明不应该被提升(不包括普通变量和函数表达式

下面这段代码在不同浏览器中有不同的表现,ES2015中说在if中的的函数声明不应该被提升(不包括普通变量和函数表达式),但是并不是所有浏览器都如此

1
2
3
4
5
6
7
8
9
10
11
foo();
var a = true;
if (a) {
function foo() {
console.log(1);
}
} else {
function foo() {
console.log(2);
}
}

在Chrome53和Firefox49中,均没有把foo函数提升,均提示not a function。但是在10.12的Safari10中却被提升并输出2。

在MDN中其实写了这段话

1
2
3
4
5
6
if (shouldDefineZero) {
function zero() { // DANGER: compatibility risk
console.log("This is zero.");
}
}
ES2015 says that if shouldDefineZero is false, then zero should never be defined, since the block never executes. However, it's a new part of the standard. Historically, this was left unspecified, and some browsers would define zero whether the block executed or not.

意思就是由于历史原因有些浏览器不管if块有没有执行,都会把函数声明提升,同时也注明了有兼容性风险(compatibility risk),所以还是不要在if中定义函数吧