We know that declaring variables will be promoted:
var a = 1;
//上面一行相当于下面这样:
var a;
a = 1;
At the same time, function declarations will also be promoted:
foo();
function foo(){};
//上面两行相当于下面这样:
var foo;
foo = function (){};
foo()
So, when there are both variable and function declarations, who will be promoted to the higher level? How to sort? For example:
var a = 1;
foo();
function foo(){};
is that so?
var a;
var foo;
a = 1;
foo = function(){};
foo();
Because I saw this sentence in "JAVASCRIPT You Don't Know", I was a little confused:
Function declarations and variable declarations will be promoted. But a noteworthy detail is that functions are promoted first, then variables. Function declarations are hoisted before ordinary variables.
So it will be sorted like this:
var foo;
foo = function(){};
var a;
a = 1;
foo();
Solve the sorting rules, thank you!
This statement of "improvement first" is actually a misunderstanding. This is just a superficial appearance. The specifications are in no particular order (if you are interested in the implementation of V8, you can read here).
var
的提升是声明跟赋值分开,function
Improvement is the whole improvement, soIt will become like this
So there is the effect of the function being promoted first.
First of all, we can divide it into 4 pieces of content
We want to know what the sorting format looks like after promotion?
The current known condition is that variable declaration will be promoted to before variable assignment, so we can put the variable declaration in the first two digits first, regardless of its internal order for the time being:
Next, let’s determine the internal ordering of declaration and assignment modules respectively.
In order to conduct experiments, we expanded the foo function, so the current order is:
Don’t worry about why we changed it like this. Let’s continue the experiment. We will understand it during the experiment.
In order to facilitate understanding, the experiment was conducted in two times.
First: we experiment with the variable declaration module.
Then: we experiment with the variable assignment module.
Let’s do the experiment:
Based on the experimental results, our final ranking result is: