在 if 语句中提升 Javascript 函数

标签 javascript hoisting

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/

相关文章:

javascript - HTML 根据滚动大小自动隐藏文本(如在 Gmail 中)?

Javascript 提升自执行功能

scala - Scala 编译器会提升正则表达式吗

javascript - 在浏览器中为单个网页执行多少个 JavaScript 程序?

javascript - 查找最接近的单选按钮组的值

javascript onclick 不适用于 P 元素

javascript - 填写所有字段后提交表单

javascript - Phonegap 应用程序翻译

c# - 为什么 C# 中不存在提升?

javascript - Javascript 中的提升/返回变量