js 预编译环节的变量提升

有些东西需要先告诉你怎么用,再去理解定义

关于变量的提升
function test () {
  console.log(a)
  var a = 100
  console.log(a)
};
test () // undefined  // 100
执行步骤
function test () {
  var a = undefined
  console.log(a)
  a = 100
  console.log(a)
}

关于函数的提升
function test () {
  console.log(a)
  function a () {}
  console.log(a)
  function b () {}
  console.log(b)
};
test() // function a () {} // function a () {} // function b () {}
执行步骤
function test () {
  var a = undefined
  var b = undefined
  a = function a () {}
  b = function b () {}
  console.log(a)
  console.log(a)
  console.log(b)
}

关于变量和函数的混合提升
function test () {
  console.log(a)
  var a = 100
  console.log(a)
  function a () {}
  console.log(a)
  function b () {}
  console.log(b)
};
test() // function a () {}  // 100  // 100 // function b () {}
执行步骤
function test () {
  var a = undefined
  var b = undefined
  a = function a () {}
  b = function b () {}
  console.log(a)
  a = 100
  console.log(a)
  console.log(a)
  console.log(b)
}

关于形参和变量混合提升
function test (a) { // 定义函数中用来接收参数 这个就是形参
  console.log(a)
  var a = 100
  console.log(a)
};
// 调用函数的时候传具体的参数 这个参数就是实参
test(1) // 1 // 100
执行步骤
function test (a) {
  var a = undefined
  a = a // 右边的a是形参
  console.log(a)
  a = 100
  console.log(a)
}

关于形参和函数的混合提升
function test (a) {
  console.log(a)
  function b () {}
  function a () {}
  console.log(a)
  console.log(b)
};
test(1) // functioin a () {} // function a () {} // function b () {}
执行步骤
function test (a) {
  var a = undefined
  var b = undefined
  a = a // 右边的a是形参
  b = function b () {}
  a = function a () {}
  console.log(a)
  console.log(a)
  console.log(b)
}

关于形参和变量和函数的混合提升
function test (a) {
  console.log(a);
  var a = 100;
  console.log(a)
  function a () {}
  console.log(a)
  function b () {}
  console.log(b)
};
test(1) // function a () {} // 100 // 100 // function b () {}
执行步骤
function test (a) {
  var a = undefined
  var b = undefined
  a = a // 右边的a是形参
  a = function a () {}
  b = function b () {}
  console.log(a)
  a = 100
  console.log(a)
  console.log(a)
  console.log(b)
}

if 判断语句不影响变量提升 (if是执行语句,而变量提升属于预编译环节;js先编译后执行)
function test () {
  console.log(a)
  if (false) {
    var a = 100
    console.log(a)
  }
};
test() // undefined 
执行步骤
function test () {
  var a = undefined
  console.log(a)
  if (false) {
    a = 100
    console.log(a)
  }
}


总结:
函数内部js的预编译环节执行顺序如下
1. 将形参,变量,函数对应的变量提升到该函数的顶部(执行期上下文顶部)
2. 将形参,函数赋值到对应的变量 (先形参,后函数)
3. 按顺序执行   

 

posted @ 2019-06-14 13:55  郭扬  阅读(173)  评论(0编辑  收藏  举报