js中的变量提升和函数提升

本文详细解析了JavaScript的词法分析和执行阶段,重点介绍了变量提升和函数提升的概念。通过实例展示了变量和函数声明如何在预编译阶段被提升到作用域顶部,以及函数声明与函数表达式的区别。此外,还探讨了函数内部的提升规则,帮助理解JavaScript的执行上下文。
摘要由CSDN通过智能技术生成

js 执行

  1. 词法分析阶段:包括分析形参、分析变量声明、分析函数声明三个部分。通过词法分析将我们写的 js 代码转成可以执行的代码。
  2. 执行阶段

变量提升

  • 只有声明被提升,初始化不会被提升
  • 声明会被提升到当前作用域的顶端

🌰 1:

console.log(num)
var num
num = 6

预编译之后

var num
console.log(num) // undefined
num = 6

🌰 2:

num = 6
console.log(num)
var num

预编译之后

var num
num = 6
console.log(num) // 6

🌰 3:

function bar() {
    if (!foo) {
        var foo = 5
    }
    console.log(foo) // 5
}
bar()

预编译之后

function bar() {
    var foo // if语句内的声明提升
    if (!foo) {
        foo = 5
    }
    console.log(foo)
}
bar()

函数提升

  • 函数声明和初始化都会被提升
  • 函数表达式不会被提升

🌰 1: 函数声明可被提升

console.log(square(5)) // 25
function square(n) {
    return n * n
}

预编译之后

function square(n) {
    return n * n
}
console.log(square(5))

🌰 2: 函数表达式不可被提升

console.log(square) // undefined
console.log(square(5)) // square is not a function
var square = function(n) {
    return n * n
}

预编译之后

var square
console.log(square)
console.log(square(5))
square = function() {
    return n * n
}

🌰 3:

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

预编译之后:

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

函数提升在变量提升之前

🌰 1:

console.log(foo) // 会打印出函数

function foo() {
    console.log('foo')
}
var foo = 1

🌰 2:

var foo = 'hello' // hello
;(function(foo) {
    console.log(foo)
    var foo = foo || 'world'
    console.log(foo) //hello
})(foo)
console.log(foo) // hello

预编译之后

var foo = 'hello'
;(function(foo) {
    var foo
    foo = 'hello' // 传入参数的foo值
    console.log(foo) // hello
    foo = foo || 'world' // foo有值为hello,所以没有赋值为world
    console.log(foo) // hello
})(foo)
console.log(foo) // hello, 打印的事全局作用域下的var foo = 'hello'
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值