One, the variable declaration promotion
Hoisting English [' hɔɪstɪŋ] us [' hɔɪstɪŋ]
N. Lifting and lifting
V. To put the ... Hang Up, rise (hoist present participle)
First look at a chestnut
var cc = ' Hello ';
function foo () {
console.log (cc);
var cc = ' world ';
Console.log (cc);
Foo ();
Console.log (CC);
Here will be output undefined
, 'world'
'hello'
There are two main points of knowledge here:
1. Scope
2. Variable declaration Promotion
JavaScript is an interpretive language, and when code is executed in an interpreter (such as the chrome V8 engine), there is a pre resolution process that promotes the variable declaration and function declaration to the front of the current scope, which is called a declaration elevation (hoisting)
Looking at the example above, the code has two-layer scopes, global scopes, and function scopes foo
, and foo
the variable declarations in the pre-parsing process are elevated to the front of the function scope, so the code becomes this way:
var cc = ' Hello ';
function foo () {
var cc;
Console.log (cc);
CC = ' world ';
Console.log (cc);
Foo ();
Console.log (CC);
When the first log is executed, the variable cc is only declared and not assigned, so the print isundefined
Second, function declaration promotion
There are two ways to declare a function: function declarations and function expressions
function declaration Functions
foo (A, b) {return
a + b;
}
function Expression
var foo = function (A, b) {return
a + b;
}
When the parser loads data into the execution environment, it does not discriminate between function declarations and function expressions. The parser takes the lead in reading the function declaration and making it available (accessible) before executing any code, and the function expression must wait until the parser executes to the line of code it is in before it is actually interpreted.
Of course, function declarations and function expressions can be used at the same time, for example var a = function b(){}
, the result is a function expression only, B will be automatically ignored, so only the effect of variable elevation will occur.
Summarize
The above is the entire content of this article, I hope the content of this article for everyone's study or work can bring certain help, if you have questions you can message exchange.