Analysis of JavaScript variable declaration elevation (Hoisting) and javascripthoisting
I. Variable declaration escalation
Hoisting English ['h has been st most recent] us ['h has been st most recent]
N. Lifting and lifting
V... Raise (current Word Segmentation of hoist)
Let's look at a chestnut.
var cc = 'hello';function foo(){ console.log(cc); var cc = 'world'; console.log(cc);}foo();console.log(cc);
The output is as follows:undefined
,'world'
,'hello'
There are two main knowledge points:
1. Scope
2. Variable declaration escalation
JavaScript is an explanatory language. When the code is executed in the interpreter (such as Chrome's V8 engine) environment, there will be a pre-resolution process, at this time, the variable declaration and function declaration are promoted to the forefront of the current scope. This behavior is called Hoisting)
Let's take a look at the example above. This code has two levels of scopes, global scopes and functions.foo
Scope, andfoo
The variable declaration in the pre-resolution process will be promoted to the front of the function scope, so the code will become like this:
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 declared and not assigned a value.undefined
Ii. Improvement of function declaration
There are two methods to declare a function: function declaration and function expression.
// Function declaration function foo (a, B) {return a + B;} // function expression var foo = function (a, B) {return a + B ;}
When the parser loads data to the execution environment, the function declaration and function expression are not treated equally. The parser will first read the function declaration and make it available (accessible) before executing any code. As for the function expression, it must wait until the parser executes to its line of code, to be interpreted and executed.
Of course, you can also use the function declaration and function expression at the same time, as shown in figurevar a = function b(){}
The result is only a function expression, and B will be automatically ignored, so only variables will improve the effect.
Summary
The above is all about this article. I hope this article will help you in your study or work. If you have any questions, please leave a message.