关于javascript:什么是变量提升

36次阅读

共计 1174 个字符,预计需要花费 3 分钟才能阅读完成。

解释下变量晋升?✨


JavaScript 引擎的工作形式是,先解析代码,获取所有被申明的变量,而后再一行一行地运行。这造成的后果,就是所有的变量的申明语句,都会被晋升到代码的头部,这就叫做变量晋升(hoisting)。

console.log(a) // undefined

var a = 1

function b() {console.log(a)
}
b() // 1

下面的代码理论执行程序是这样的:

第一步:引擎将 var a = 1 拆解为 var a = undefineda = 1,并将 var a = undefined 放到最顶端,a = 1还在原来的地位

这样一来代码就是这样:

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

a = 1

function b() {console.log(a)
}
b() // 1

第二步就是执行,因而 js 引擎一行一行从上往下执行就造成了以后的后果,这就叫变量晋升。

原理详解请移步,预解释与变量晋升

what’s variable promotion ?

The way of javascript engine work is to parse the code first, getting all of varibales that be declared, and then run it line by line.

The result of that all variable delcaration statements will be promoted to the head of code, which is called variable hoisting.

console.log(a) // undefined

var a = 1

function b() {console.log(a)
}
b() // 1

the actual execution sequence of the above code is as follow:

Step 1: the engine will split var a = 1 to var a = undefined and a = 1, and place the var a = undefined to the top, a = 1 still in the original place.

This way of code is as follow:

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

a = 1

function b() {console.log(a)
}
b() // 1

Step 2 is execution, so the JS engine execute line by line from top to bottom cause the result of the present, which is called variable hoisting.

If you want to move to the detailed explanation of the principle, pre-explanation and variable promotion

正文完
 0