(function() { var x=foo (); var foo=function foo () { return ' Foobar ' }; return x; }) ();
This code runs after the error: Uncaught Typeerror:foo is not a function
The reason is that the declaration of the variable foo is lifted, the subsequent assignment, and the function expression is not lifted, so when the code runs to Var x=foo (); When
Foo () is undefined.
Can put Var x=foo (); Put the variable foo before executing:
(function() { var foo=function foo () { return ' Foobar ' }; var x=foo (); return x; }) ();
The function declares the entire promotion to the top of the scope, such as writing:
(function() { var x=foo (); function foo () { return ' Foobar ' } return x; }) ();
Let's look at an example:
var foo = {N:1}; (function//Note here, pass in parameter foo console.log (FOO.N); FOO.N=3//global variable re-assignment ,var foo={n:2//local variable foo is re-assigned Console.log ( FOO.N); }) (foo); Console.log (FOO.N); //global variable is already N:3
- First step: Pre-compile, VAR global variable foo, anonymous function functions, var local variable foo
- Second step: The code performs the calculation from top to bottom, from left to right:
- Assign the global variable foo foo={n:1}; Note: This value is an object, which belongs to the reference type;
- anonymous function passed in parameter foo={n:1} self-executing;
- Console.log (foo); number 1;
- Because of the Foo local variable, the foo variable is assigned a value of Foo={n:3}, and the parameter value of the reference type is changed, and the global foo variable is re-assigned the value Foo={n:3};
- The local variable foo is re-assigned foo={n:2};
- Console.log (foo); number 2;
- global variable Foo={n:3}, so Console.log (foo); hit the number 3;
about the var x1=foo (); var X2=foo; There is no parenthesis difference
A function is an instance of a type called a function reference, so it is an object. The object is stored in memory, and the function name is a pointer to the object.
A function can be passed as a parameter to another function, or it can be a return value of a function, or it can be re-assigned.
In simple terms, X1 is the return value of function foo (), and X2 is the function foo () itself.
(function() { var foo=function foo () { return ' Foobar ' }; var x=foo; return x; }) (); // function foo () {return ' Foobar '}
JavaScript Variable Declaration Promotion