[JS] Topic - variable and function hoisting

Ref: 深入理解js的变量提升和函数提升

 

 一、变量提升

简直就是es5的遗毒!

console.log(global); // undefined 竟然能打印?因为变量提升,下一行就有定义
var global = 'global';
console.log(global); // global
 
function fn () {
  console.log(a); // undefined   竟然能打印?因为变量提升,下一行就有定义
  var a = 'aaa';   console.log(a); // aaa } fn();

实际运行的代码过程,也就是编译器自己做了些手脚。

var global; // 变量提升,全局作用域范围内,此时只是声明,并没有赋值
console.log(global); // undefined
global = 'global'; // 此时才赋值
console.log(global); // 打印出global
 
function fn () {
  var a; // 变量提升,函数作用域范围内
  console.log(a);
  a = 'aaa';
  console.log(a);
}
fn();

 

 二、函数提升

js中创建函数有两种方式:函数声明式函数字面量式。只有函数声明(第一种)才存在函数提升!

console.log(f1); // function f1() {}   
console.log(f2); // undefined  
function f1() {}  // 这种传统意义上的,就可以 var f2 = function() {}

 

实际运行的代码过程,也就是编译器自己做了些手脚。

function f1() {} // 函数提升,整个代码块提升到文件的最开始,函数提升起来了,嘿嘿
console.log(f1);   
console.log(f2);   
var f2 = function() {}

 

posted @ 2018-04-15 17:29  郝壹贰叁  阅读(198)  评论(0编辑  收藏  举报