Function Excuted Before Creation
Solution 1:
This happens because of variable hoisting. See this answer for more info
Some docs about this: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var#var_hoisting
If you type it like this, it won't work:
a();
a = function(){
alert('a');
}
Solution 2:
Code that is within functions and objects will be run whenever that function or object is called. If it is called from code that is directly in the head or body of the page then its place in the execution order is effectively the spot where the function or object is called from the direct code.
See the reference here.
And in our case the function will give the error as you can see the example here.
Solution 3:
It's because function a() is declared via Function Declaration syntax, and Function Declaration are executed right after the script is parsed. With other syntax, Function Expression, like this:
var b = function(){
alert('b');
}
it won't work (see example).
More info: http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/
Post a Comment for "Function Excuted Before Creation"