JS的变量声明提升和函数声明提升

2018/01/16

一. 变量声明提升

在作用于内代码被执行之前,作用域中变量的声明会被提升至作用域的顶部。

var v = 'Hello World';
function test (){
  console.log(v);
  var v = 'I love you';
};
test ();// 输出 undefined

以上代码等同于

var v;
v = 'Hello World';
function test (){
  var v;
  console.log(v);
  v = 'I love you';
};
test ();// 输出 undefined

二.函数声明提升

定义函数的有两种方式,函数声明和函数表达式。

在作用于内代码被执行之前,作用域中的函数声明会将函数声明和函数体一并提升到作用域的顶部。

test(); // 输出 100
function test(){
    console.log(100);
}

在作用于内代码被执行之前,作用域中的函数表达式仅会将函数声明提升到作用域的顶部。

console.log(test); // undefined
test(); // Uncaught TypeError: test is not a function
var test = function(){
    console.log(100);
}

此外要注意的是,函数声明提升重名时最后面会覆盖前面的,且函数声明优先级高于变量声明。

test();// 输出 2
function test(){
    console.log(1);
}
function test(){
    console.log(2);
}
var test = 3;

文章导航