变量提升
在 ES6 出来之前,没有块级作用域,只有全局作用域 和 函数作用域。
变量提升指的是 将变量声明提升到它所在作用域的最开始部分。
例子:
console.log(foo); // undefined var foo = '变量提升'; console.log(foo) // 变量提升
相当于:
var foo; console.log(foo) // undefined foo = '变量提升'; console.log(foo); // 变量提升
函数提升
函数创建有两种方式,一种是函数声明形式,一种是函数字面量形式,而只有 函数声明形式 才有函数提升。
例子:
console.log(bar); // f bar() { console.log(123) } console.log(bar()); // undefined var bar = 456; function bar() { console.log(123); // 123 } console.log(bar); // 456 bar = 789; console.log(bar); // 789 console.log(bar()) // bar is not a function
相当于:
// 函数提升,函数提升优先级高于变量提升 var bar = function() { console.log(123) }; // 变量提升,变量提升不会覆盖(同名)函数提升,只有变量再次赋值时,才会被覆盖 var bar; console.log(bar); console.log(bar()); // 变量赋值,覆盖同名函数字面量 bar = 456; console.log(bar); // 再次赋值 bar = 789 console.log(bar); console.log(bar())
优先级
函数提升优先级高于变量提升,且不会被同名变量声明时覆盖,但是会被变量赋值后覆盖。
例子:
var getName = function(){ console.log(2); } function getName (){ console.log(1); } getName();
相当于:
function getName (){ console.log(1); } var getName = function(){ console.log(2); } getName(); // 2