变量提升和函数提升

73 阅读1分钟

变量的声明会提到函数的顶部,变量赋值并不会提升。

1.变量提升

// 变量提升
foo();
function foo(){
  console.log('hello')
}

输出结果:hello

2.函数表达式

foo2(); // 异常
var foo2 = function(){
  console.log('hello2')
}

实际执行过程是

var foo2;
foo2();
foo2 = function(){
  console.log('hello2')
}

直接在foo2()报错

3.变量提升和函数提升同时存在

var a = true
foo()
function foo() {
  if (a) {
    var a = 10
  }
  console.log(a)
}

实际执行过程是

var a = true
foo()
function foo() {
  var a
  if (a) {
    a = 10
  }
  console.log(a)
}

输出结果:undefined

4.变量提升和函数提升的优先级

  • 函数的提升高于变量的提升。
  • 对于相同名称的变量声明是不会覆盖掉函数的声明的。
  • 但是变量的赋值是会覆盖函数。
console.log(a)
console.log(a())
var a = true
function a() {
  console.log(2)
}
a = 3
console.log(a)
console.log(a())

相当于

function a() {
  console.log(2)
}
var a             //变量a无法覆盖函数a,两者可以并行存在
console.log(a)    // 输出function a
console.log(a())  // 2
a = 1
a = 3
console.log(a)    // 2
console.log(a())  // Error

5.函数的名称是只读的

函数的名称是只读的,所以不能在函数内部修改函数的名称。因此,函数内部再对函数名称赋值修改是无效的。

var test = "hello world";
(function test() {
  test = "test data";
  console.log(test);
})();

因为函数内部不能修改函数修改,所以test="test data" 并没有起作用,可有可无的。

输出结果:

image.png