In the wrong.js
file below you'll get JSLint errors and after Alloy compiles both function declarations will be there. The right.js
file shows how it should be done.
Last active
December 21, 2015 04:19
-
-
Save FokkeZB/6248899 to your computer and use it in GitHub Desktop.
Declaring a function in a code block
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (OS_ANDROID) { | |
var foo = function () { | |
alert('android'); | |
} | |
} else { | |
var foo = function () { | |
alert('not android'); | |
} | |
} | |
foo(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
if (OS_ANDROID) { | |
function foo() { | |
alert('android'); | |
} | |
} else { | |
function foo() { | |
alert('not android'); | |
} | |
} | |
foo(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is because of a combination of hoisting and lack of block-level scope. Function declarations (the form you use in wrong.js) are hoisted entirely to the top of the scope, which would be outside your
if(OS_ANDROID)
block. That means the variablefoo
, and the function is contains are now moved outside the if block. And the second declaration overwrites the first.Try it in your browser console:
With the function statement (the form in your right.js example), the declaration of the variable
foo
is hoisted to the top of the scope, but its value assignment (putting the function inside that variable) is kept in its original place.