If I do this in my <head> tag:
<script type="text/javascript" src="foo.js"></script>
And inside foo.js I do this:
var foo = new Foo();
function Foo()
{
//code here
}
Would this code reliably instantiate the variable foo even though its included above the function definition, or should I move it instead to the bottom of the file, like this:
function Foo()
{
//code here
}
var foo = new Foo();
Your example will work in any browser that follow the ECMAScript standard (all do at least with regards to this question).
See sections 10.3-10.5 of the specification.
First the local scope is set up and just thereafter the function body is actually run.
Read 10.5 (the section is really not very long) to understand why @meder’s answer is right.
If you don’t want to read the specs yourself:
10.5 tells to declare variables in that order (overwriting if a some name occurs twice):
Inheriting from outer scope = setting will affect the outer scope:
Local scope = setting won’t affect the outer scope:
undefinedif none, yet)All in all:
Returns the function x itself:
Returns the parameter x:
Returns the inner function x:
Also returns the inner function x:
Returns 42:
Returns the second argument:
Returns 2 when
xis called the second time, as x is set to the inner function: