variable hoisting (example)

Variable promotion (use variables first, then declare variables)

console.log(d) //报错:is not definded


//变量提升
console.log(d) //undefined 此时执行的该行代码的时候d还未赋值, 所以结果是undefined
var d = 5

Advanced Variable Hoisting

the case

var a = 10,b = 20,c
//定义函数并直接调用
;(function(){
    
    
  		//由于变量提升的原因,导致此时的不再是全局的a,此时的a是一个局部变量,而在当前行的a未赋值,所以a的值是undefined
    console.log(a,b)// undefined 20  a: 变量提升
    var a = b = 30//a=30 b=30
    conso1e.log(a,b,c) // 30  30 undefined   c: 变量提升
    var c = 1 //
    console.log(c) // 1
})()
console.log(a,b,c) // 10 30 undefined
var a = 5, b, c = 6
;(function() {
    
    
    conso1e.log(a, b, c) //undefined, undefined, undefined//此时a, c是变量提升  b:全局变量
    var a = 5
    var c = 6
    b = c //b=6
    console.log(a, b, c) // 5 6 6
})()
console.log(a, b, c) // 5 6 6
var a, b, c = 5 //全局变量
//定义函数并直接执行函数 后面不用对函数进行调用
;(function() {
    
    
    console.log(a, b, c) //undefined,undefined,undefined
    //局部变量
    var a = 1
    var b = 2
    var c = 3
    conso1e.log(a, b, c) //1, 2, 3
})()
conso1e.log(a,b,c) //undefined,undefined,5

Guess you like

Origin blog.csdn.net/weixin_45753871/article/details/109453276