变量提升与函数提升

1.变量声明提升

(1) var声明的变量,在定义语句之前就可以访问到,值为undefined

var a = 3
function fn () {
    console.log(a);//undefined
    var a = 4
}
fn()

相当于

var a = 3
function fn () {
	var a
    console.log(a);//undefined
    a = 4
}
fn()

2.函数声明提升

(2)function声明的函数,在之前就可以直接调用,值为函数定义(对象)

 var a = 3
 fn()
 function fn () {
     console.log('fn执行了');
     console.log(a);//undefined
     var a = 4
 }

 b()//b is not a function
 var b = function fn(){
     console.log('bfn执行了');
 }

fn()可调用,b不可调用,因为b是变量,变量提升后,默认值为undefined,无法作为函数执行

3.测试题


var a = function () {
    console.log(1)
}

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


执行顺序是:1. 变量a提升 ->undefined
2. 函数提升->替换掉 a-> (){console.log(2)}
3. 执行到
js var a = function () { console.log(1) }时,a又被替换为a->(){console.log(1)}
所以最后输出1

先执行 变量提升,再执行函数提升

if(!(b in window)){
    var b = 1
}
console.log(b); //undefined

b变量提升,存在于window中 所以b in window 返回true ,再取反,为false,所以b没有赋值,为undefined

 var c = 1
 function c(c) {
     console.log(c);
     var c = 3
 }
 c(2) //c is not a function

先执行 变量提升,再执行函数提升 然后再执行赋值,即c=1,所以c为数值,不是方法

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值