Skip to content

Latest commit

 

History

History
79 lines (67 loc) · 2.61 KB

JS变量提升.md

File metadata and controls

79 lines (67 loc) · 2.61 KB

JavaScript变量提升

JavaScript中变量声明与函数声明都会被提升到作用域顶部,优先级依次为:变量声明 函数声明 变量赋值

变量提升

var的变量提升

console.log(a); // undefined
var a = 1;
console.log(a); // 1
// console.log(b); // ReferenceError: b is not defined

为了显示ab的区别,打印了一下未声明的变量b,其抛出了一个ReferenceError异常,而a并未抛出异常,其实对a的定义并赋值类似于以下的操作,将a的声明提升到作用域最顶端,然后再执行赋值操作。

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

let的变量提升

关于这个问题目前有所分歧,但在ES6的文档中出现了var/let hoisting字样,也就是说官方文档说明letvar一样,都存在变量提升,我觉得能够接受的说法是

let 的「创建」过程被提升了,但是初始化没有提升。  
var 的「创建」和「初始化」都被提升了。  
function 的「创建」「初始化」和「赋值」都被提升了。

js中无论哪种形式声明var,let,const,function,function*,class都会存在提升现象,不同的是,var,function,function*的声明会在提升时进行初始化赋值为 undefined,因此访问这些变量的时候,不会报ReferenceError异常,而使用let,const,class声明的变量,被提升后不会被初始化,这些变量所处的状态被称为temporal dead zone,此时如果访问这些变量会抛出ReferenceError异常,看上去就像没被提升一样。

https://blog.csdn.net/jolab/article/details/82466362
https://www.jianshu.com/p/0f49c88cf169
https://stackoverflow.com/questions/31219420/are-variables-declared-with-let-or-const-not-hoisted-in-es6

函数声明提升

函数声明会将声明与赋值都提前,也就是整个函数体都会被提升到作用域顶部

s(); // 1
function s(){
    console.log(1);
}

函数表达式只会提升变量的声明,本质上是变量提升并将一个匿名函数对象赋值给变量

console.log(s); // undefined
var s = function s(){
    console.log(1);
}
console.log(s);  // f s(){console.log(1);}

优先级

var s = function(){
    console.log(0);
}
function s(){
    console.log(1);
}
s(); // 0

其在JS引擎的执行的优先级是 变量声明 函数声明 变量赋值

var s; // 变量声明

function s(){ //函数声明
    console.log(1);
}

s = function(){ // 变量赋值
    console.log(0);
}

s(); // 0