简体   繁体   中英

Javascript function hoisting inside of if statements

What's the deal with javascript function hoisting inside of if statements? Does js just not do it? The following code, when run in a browser works just fine. It will alert "hey" after two seconds.

<script>
setTimeout(hey,2000)
function hey(){
    alert('hey')
}
</script>

But add a trival if statement around this:

<script>
if(true){
setTimeout(hey,2000)

function hey(){
    alert('hey')
}
}
</script>

and suddenly it complains that hey is not defined .
Now if you change the callback from hey to function(){hey()} , like this:

<script>
if(true){
setTimeout(function(){hey()},2000)

function hey(){
    alert('hey')
}
}
</script>

then it starts working again, even with the if statement. So what's going on?

Firefox doesn't hoist function declarations in blocks , apparently. The behavior you're seeing is specific to Firefox, and documented nearly identically elsewhere.

To paraphrase:

Works:

 if ( hasRequiredJQueryVersion ) { // Test data here // Library code here } 

Works everywhere except Firefox:

 if ( true ) { testFunction(); function testFunction() { alert('testFunction called'); } } 

This is behavior you should avoid, as it is specific to Firefox, even though Firefox's behavior may technically be correct.

The third example is consistent w/ the second: setTimeout isn't actually calling hey , so doesn't care that it hasn't been defined. It is only when the timeout occurs that hey is called, by which point is has been defined.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM