javascript中的变量提升和函数提升详解

我们用循序渐进的例子来看JavaScript中的变量提升和函数提升。

实践一:变量声明提升的优先级高于函数声明提升

比较下面两个例子,将会输出同样的结果:

 

!function(){
    console.log(haha); // 输出haha函数
    function haha(){
        console.log('i am haha');
    }
    var haha = 1;
    console.log(haha); // 输出 1
}();

vs

 

!function(){
    console.log(haha); // 输出haha函数
    var haha = 1;
    function haha(){
        console.log('i am haha');
    }
    console.log(haha); // 输出 1
}();

其实他们都可以变化成这样, 上面两个执行的顺序是这样的:

 

!function(){
    var haha; // 变量先提升
    // 再提升函数
    function haha(){
        console.log('i am haha');
    }
    console.log(haha); // 输出函数
    haha = 1; // 重新被赋值,类型从函数变为数值
    console.log(haha); // 输出1
}();

是不是走到这儿,瞬间秒懂...
实践二:局部变量定义时,通过var声明和不用var声明直接使用带来的问题

 

!function() {
  var t=1;
  function hello(){
    t=2;
    console.log(t);
  }
  hello(); // 2
  console.log(t); // 2
}();
// 这里做出解释:
// 函数hello内部的t,没有通过var声明,自动变成闭包中的全局变量,所以hello内部的t,改变了外部t的值。

vs

 

!function(){
  var t=1;
  function hello(){
    var t=2;
    console.log(t);
  }
  hello(); // 2
  console.log(t); // 1
}();
// 这里做出解释:
// 函数hello内部通过var声明并且定义了变量t,没有更改外部的t。

vs

 

!function(){
  var t=1;
  function hello(){
    console.log(t);
    var t=2;
    console.log(t);
  }
  hello(); // undefined 2
  console.log(t); // 1
}();
// 这里做出解释:
// 在函数hello内部,有变量提升,其实执行的顺序如下:
// var t;
// console.log(t); // undefined
// t=2;
// console.log(t); // 2
// 而在hello之外,变量t的值仍旧是1,所以输出1

实践三: 实践二的补充,函数提升在代码书写顺序上的不同而带来的问题

 

!function(){
  function hello(){
    foo();
    function foo(){
      console.log('i am foo');
    }
  }
  hello(); // i am foo
}();
// 解释:
// 在函数hello内部,函数式声明,foo提升到了上面,如下:
// function foo(){}
// foo();
// 所以函数能够正常执行

vs

 

!function(){
  function hello(){
    foo();
    var foo=function(){
      console.log('i am foo');
    }
  }
  hello(); // 错误 执行后not a function
}();
// 解释:通过函数字面量的形式来声明函数,在此处是变量提升,得到undefined,因为undefined无法执行,所以会报错,按照下面的顺序来理解:
// var foo; 
// foo();
// foo = function(){};
// 所以 就会报错:Uncaught TypeError: foo is not a function

总结:函数提升和变量提升,其实也差不多就这样,可能也会有很多变化形式,但主旨我们都已经说了,我们在写代码的时候,为了让程序更易懂,更容易维护,尽量规避这些问题。

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Wang's Blog

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值