In JavaScript, a variable or function is used before declaring a variable or function, which creates an error. These will appear in many JS written questions.
First look at the following question:
1(function( ) {2 varx =foo ();3 varFoo =functionfoo () {4 return"Foobar";5 } 6 returnx;7})( );
Q: The return value of the above function is ()
A, type Error
B, Foobar
C, undefined
D, foo ()
the answer should be a, not d. For that reason, we should all know. The problem is in this code:
var foo = function foo () {
return "Foobar";
}
Declaring the variable Foo with VAR will raise it to the front of the function body, but the function expression will not be promoted as follows:
var foo;
var x = foo ();
foo = function foo () {...};
Therefore, when the function executes to var x = foo (), the function foo () has not been declared, and therefore the type error occurs: Typeerror:foo is not a function.
There are two ways to solve the above code problem:
1.
(function() {
function foo () {
Return "Foobar"
var x = foo ();
Return
})( );
2, remove the Var foo, directly using function () to declare foo (), so that Foo () will also be promoted to the front
1 (function() {2 var x = foo (); 3 function foo () {4 return "Foobar" ;5 6 return7}) ( );
JavaScript variable declaration and function declaration promotion