What You Didn't Know About JavaScript—Variable Hoisting

foreword

For JavaScript, var a = 2; is two operations. var a is a task of the compile phase, and a = 2 is a task of the execution phase. Therefore, all declarations are "moved" to the topmost of their respective scopes before the code is executed. This process is "promote”。


1. Variable declaration and assignment?

Declarations come first, assignments follow.
Only the declaration itself is hoisted, while assignments or other execution logic is left in place.

console.log(a); // undefined
var a = 10;

// 等价于
var a;
console.log(a); // undefined
a = 10;

2. Function declaration

The function declaration itself is hoisted,However, operations including assignment of function expressions are not hoisted(It can be understood as the operation of ordinary variables being assigned functions).

// 函数提升
bar();  // 1
function bar(){
    
    
    console.log("1");
}

// 等价于
function bar(){
    
    
    console.log("1"); 
}
bar();  // 1
// 函数表达式提升
foo(); // TypeError
bar(); // ReferenceError
var foo = function bar(){
    
    
    //...
}

// 等价于
var foo;
foo(); // TypeError
bar(); // ReferenceError
foo = function(){
    
    
    var bar = ...
}

3. Function priority

Functions are promoted first, and ordinary variables are promoted later.
The following example: Since the function declaration will be promoted before the ordinary variable, the subsequent var foo is a repeated declaration and ignored.

foo(); // 1
var foo;
function foo() {
    
    
    console.log("1");
};
foo = function() {
    
    
    console.log("2");
};

// 等价于
function foo() {
    
    
    console.log("1");
};
foo(); // 1
foo = function() {
    
    
    console.log("2");
};

Summarize

Be careful to avoid duplicate declarations, especially when ordinary var declarations and function declarations are mixed together, otherwise it will cause a lot of problems!

Guess you like

Origin blog.csdn.net/yan_danfeng/article/details/129284579