变量提升 ( hoisting )

 

一 概述

JavaScript引擎在预编译时,会将声明(函数声明、变量声明)自动提升至函数或全局代码的顶部。但是赋值不会提升。

Because variable declarations (and declarations in general) are processed before any code is executed, declaring a variable anywhere in the code is equivalent to declaring it at the top. This also means that a variable can appear to be used before it's declared. This behavior is called "hoisting", as it appears that the variable declaration is moved to the top of the function or global code.

It's important to point out that the hoisting will affect the variable declaration, but not its value's initialization. The value will be indeed assigned when the assignment statement is reached:

二 var声明的变量,在非严格模式、严格模式都会提升

 

例一 非严格模式

function hoisting(){
    // 如果变量未提升,会报错 Uncaught ReferenceError: saint is not defined
    console.log(saint);
    var saint = 'Aioria';
    console.log(saint);
}
hoisting();

例二 严格模式

var saint = 'Orpheus';
function hoisting(){
    console.log(saint);
    var saint = 'Aioria';
    console.log(saint);
}
hoisting();

例三 函数

function test(){
    console.log(name,hello,welcome);
    var name = 'Tom';
    var hello = function(){
        console.log('hello~');
    };
    function welcome(){
        console.log('welcome~');
    }
    hello();
    welcome();
}

test();

三 let声明的变量,在非严格模式、严格模式都不会提升。

function hoisting(){
    console.log(saint);
    let saint = 'Aioria';
    console.log(saint);
}
hoisting();

原文地址:https://www.cnblogs.com/sea-breeze/p/9006683.html