In the previous article, we talked about the sequence of variable promotion and function promotion, and then we went to check the information, especially to tidy up a bit.
On page 40th of the book, "You Don't know," it says, "The function is promoted first, then the variable ."
A code example in the book is:
foo(); //1var foo;function foo() { console.log(1);} foo = function() { console.log(2);}
This example is relatively good understanding, that is, Foo This function will be declared before the beginning of the scope, in fact, the code fragment will be understood by the engine as follows:
function foo() { console.log(1);}foo(); //1foo = function() { console.log(2);}
However, when I saw this example on the Internet, I did not understand the result of the operation at first:
console.log(foo); // function foo(){...}function foo(){ console.log("函数声明");}var foo = "变量";
I see this code output should be undefined ah, because the rule is to promote the function first, then the variable, so it should not be so?
function foo(){ console.log("函数声明");}var foo = undefined;
One of the biggest pitfalls of this understanding is that variable promotion is simply declaring a variable and not assigning a value, which is
var foo;
That's all! We usually print a variable before such a declaration is undefined because it is only declared, other places are not assigned, so it is undefined, like this:
console.log(wanc); //undefinedvar wanc = ‘66‘;
However, in the example above, the variables and functions are present, and the function foo is first promoted, then the declaration variable var foo, the process of declaring the variable does not change the value of the variable, so the top print is the function foo;
Thus a small problem leads to the thinking: there are problems to be more information, including on-line and book, compared to different people's understanding, the ultimate goal is to do know it and know its why, refueling!
Resources:
- http://bbs.csdn.net/topics/392018835
- JavaScript (ON) You don't know
A little understanding of the rules and principles of variable promotion in JS (II.)