Please see my comment to Solution 1.
This is not so easy to explain. The processing goes in two phase, and everything goes from top to bottom.
First, something like some lexical analyses goes. If there are lexical errors, whole script fails silently. On this phase, function declarations becomes known to the script, so they can go after the code when the functions are called. Then the execution phase starts from top to bottom.
This is a delicate moment. The usage of a function object depends on how it is declared. This is my illustration:
try {
b();
a();
} catch(e) { alert(e); }
var a = function() { alert("a!"); };
function b() { alert("b!"); }
In this example,
b
declared a function, it will be processed on first pass and taken into account in the execution phase. In contrast to that assignment to the function object
a
is a
statement, which is not executed at the moment of the call
a(a)
. At the moment of the call,
a
will be equal to the object
undefined
, and that throws an exception.
Note the use of ';' after statement and lack of it after the function definition; essentially, this is a
terminator after the assignment operator (assignment to the object
a
). In fact, ';' can be missing or added in both cases, but I recommend to use it exactly the way I've shown; the detecting difference will be revealed if you are using more than one statement on a line, and some other cases.
It also worth noting that if you make the code shown above a string and pass it to
eval
,
b
won't work, because the lexical phase won't be performed on the string content. The rules are the same, but there is a subtle effective difference.
And finally, a note on
main
. It looks like you have a pretty common misconception about it. This is not a fundamental feature of any language, not even C or C-like. This is a convention on the boundary between the language and the runtime environment. Even with C/C++, you will find similar constructs like "WinMain", and so on (don't tell me that is simply hides "real"
main
; this is a pure convention). In many other languages, there is no such convention; it is not fundamental in programming at all.
—SA