1. Variable declaration enhancement
hoisting English['hɔɪstɪŋ] American['hɔɪstɪŋ]
n. Lifting, lifting
v. Hang up and raise (hoist's current participle)
Let's take a look at a chestnut first
var cc = 'hello'; function foo(){ (cc); var cc = 'world'; (cc); } foo(); (cc);
Here will outputundefined
、'world'
、'hello'
There are two main knowledge points here:
1. Scope
2. Variable declaration enhancement
JavaScript is an interpretive language. When the code is executed in an interpreter (such as Chrome's V8 engine), there will be a pre-parsing process. At this time, variable declarations and function declarations will be promoted to the forefront of the current scope. This behavior is called declaration promotion (Hoisting).
Let’s look at the above example. This code has two layers of scope, global scope and function.foo
scope, andfoo
The variable declaration in it will be promoted to the front of the function scope during pre-parsing, so the code will become like this:
var cc = 'hello'; function foo(){ var cc; (cc); cc = 'world'; (cc); } foo(); (cc);
When executing to the first log, the variable cc is just declared and has not assigned a value, so the printout isundefined
2. Function declaration improvement
There are two ways to declare a function: function declaration and function expression
// Function declarationfunction foo(a, b) { return a + b; } // Function expressionvar foo = function(a, b) { return a + b; }
When the parser loads data into the execution environment, function declarations and function expressions are not treated equally. The parser will be the first to read the function declaration and make it available (accessible) before executing any code; as for function expressions, you must wait until the parser executes to the line of code where it is located before it will be truly interpreted and executed.
Of course, function declarations and function expressions can also be used at the same time, such asvar a = function b(){}
,The result is that it only has the function of function expressions, and b will be automatically ignored, so only variable promotion effect will occur.
Summarize
The above is the entire content of this article. I hope the content of this article will be of some help to your study or work. If you have any questions, you can leave a message to communicate.