Calling a function before its declaration, browser independent?
If I do this in the tag <head>:
<script type="text/javascript" src="foo.js"></script>
And inside foo.js I do this:
var foo = new Foo();
function Foo()
{
//code here
}
Whether this code will reliably create a variable foo, even if it is included above the function definition, or should I move it to the bottom of the file, for example:
function Foo()
{
//code here
}
var foo = new Foo();
Your example will work in any browser that complies with the ECMAScript standard (all at least relate to this issue).
See sections 10.3-10.5 specification .
First, a local area is created, and only after that the function body is actually executed.
Read 10.5 (the section is really not very long) to see why @meder's answer is right.
:
10.5 (, - ):
= :
- .
- .
= :
- ( ).
- arguments.
- ( , ,
undefined, )
:
x:
function x() {
return x;
}
x:
function x(x) {
return x;
}
x:
function x(x) {
return x; // the return does no harm, x is already set
function x() {} // before the actual body is evaluated
}
x:
function x(x) {
var x; // in this case a no-op
return x;
function x() {}
}
42:
function x(x) {
var x = 42; // overwrite x in local scope
return x;
function x() {}
}
:
function x(x,x) { // assign left to right, last one "wins"
return x; // arguments[0] would still name the first argument
}
2, x , x :
function x() {
x = function() { return 2; } // set x in outer scope
return 1;
}
As far as I know, JS is doing this with your code due to a lift:
var foo; //var declarations hoisted up
function Foo(){ //function declarations hoisted up
//code here
}
foo = new Foo(); //the operation
so everything should be fine. However, I did not rely solely on the upgrade because it is at least difficult for me to debug when ads are everywhere. For readability, order the code as follows:
- variable declarations
- Functions
- operations
console.log(foo); //undefined
var foo = new Foo();
console.log(foo); //Foo
function Foo(){
//code here
}
console.log(foo); //Foo
//acts like:
var foo; //var declaration hoisted up
function Foo(){} //function declaration hoisted up
console.log(foo); //undefined
foo = new Foo();
console.log(foo); //Foo
console.log(foo); //Foo
console.log(foo); //undefined
function Foo(){
//code here
}
console.log(foo); //undefined
var foo = new Foo();
console.log(foo); //Foo
//acts like:
var foo; //var declaration hoisted up
function Foo(){} //function declaration hoisted up
console.log(foo); //undefined
console.log(foo); //undefined
foo = new Foo();
console.log(foo); //Foo