- <title> function Promotion </title>
- <script language="javascript" type="Text/javascript" >
- //Declare two global functions in global object, anti-pattern
- function foo ()
- {
- Alert ("Global foo");
- }
- function Bar ()
- {
- Alert ("Global Bar");
- }
- //define global variables
- var v = "Global var";
- function Hoistme ()
- {
- Alert (typeof foo); //function
- Alert (typeof bar); //undefined
- Alert (v); //undefined
- //Why is the bar function and the variable v a corresponding function variable defined in an undefined rather than a global variable?
- //Because functions and variables with the same name are defined inside the function, regardless of where they are defined in the function and
- //And variables, they will all be promoted to the top of the function.
- Foo (); //local Foo
- Bar (); //Error, missing object
- //function declaration, variable foo and its implementation are promoted to the top of the Hoistme function
- function foo ()
- {
- Alert ("local foo");
- }
- //function expression, only the variable bar is promoted to the top of the function, the implementation is not promoted
- var bar = function ()
- {
- Alert ("local Bar");
- };
- //define local variables
- var v = "local";
- }
- (Function ()
- {
- Hoistme ();
- })();
- //function expressions and variable expressions only their declarations are promoted, function declarations are declarations and implementations of functions are promoted.
- /** because of the effect of function promotion, the Hoistme method is equivalent to
- function Hoistme ()
- {
- function declaration, variable foo and its implementation are promoted to the top of the Hoistme function
- function foo ()
- {
- Alert ("local foo");
- }
- function expression, only the variable bar is promoted to the top of the function, the implementation is not promoted (same variable elevation)
- var bar = undefined;
- Variable declaration is promoted
- var v = undefined;
- Alert (typeof foo); function
- Alert (typeof bar); Undefined
- Foo (); Local Foo
- Bar (); Error, missing object
- bar = function ()
- {
- Alert ("local bar");
- };
- v = "local";
- }
- */
- </script>
- <body>
- </body>
Promotion of functions and variable definitions in JavaScript