在 if
语句中提升 javascript 函数有什么用?难道js就是不做?以下代码在浏览器中运行时运行良好。它会在两秒后发出“嘿”的警报。
<script>
setTimeout(hey,2000)
function hey(){
alert('hey')
}
</script>
但是添加一个简单的 if
语句:
<script>
if(true){
setTimeout(hey,2000)
function hey(){
alert('hey')
}
}
</script>
然后它突然提示说hey is not defined
。
现在,如果您将回调从 hey
更改为 function(){hey()}
,如下所示:
<script>
if(true){
setTimeout(function(){hey()},2000)
function hey(){
alert('hey')
}
}
</script>
然后它再次开始工作,即使有 if 语句。那么这是怎么回事?
最佳答案
Firefox doesn’t hoist function declarations in blocks , 显然。您看到的行为是 Firefox 特有的,并且在其他地方几乎完全相同。
换句话说:
Works:
if ( hasRequiredJQueryVersion ) { // Test data here // Library code here }
Works everywhere except Firefox:
if ( true ) { testFunction(); function testFunction() { alert(‘testFunction called’); } }
这是您应该避免的行为,因为它是 Firefox 特有的,即使 Firefox 的行为可能技术上是正确的。
关于在 if 语句中提升 Javascript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27281445/