我们用循序渐进的例子来看JavaScript中的变量提升和函数提升。
实践一:变量声明提升的优先级高于函数声明提升
比较下面两个例子,将会输出同样的结果:
!function(){
console.log(haha); // 输出haha函数
function haha(){
console.log('i am haha');
}
var haha = 1;
console.log(haha); // 输出 1
}();
vs
!function(){
console.log(haha); // 输出haha函数
var haha = 1;
function haha(){
console.log('i am haha');
}
console.log(haha); // 输出 1
}();
其实他们都可以变化成这样, 上面两个执行的顺序是这样的:
!function(){
var haha; // 变量先提升
// 再提升函数
function haha(){
console.log('i am haha');
}
console.log(haha); // 输出函数
haha = 1; // 重新被赋值,类型从函数变为数值
console.log(haha); // 输出1
}();
是不是走到这儿,瞬间秒懂...
实践二:局部变量定义时,通过var声明和不用var声明直接使用带来的问题
!function() {
var t=1;
function hello(){
t=2;
console.log(t);
}
hello(); // 2
console.log(t); // 2
}();
// 这里做出解释:
// 函数hello内部的t,没有通过var声明,自动变成闭包中的全局变量,所以hello内部的t,改变了外部t的值。
vs
!function(){
var t=1;
function hello(){
var t=2;
console.log(t);
}
hello(); // 2
console.log(t); // 1
}();
// 这里做出解释:
// 函数hello内部通过var声明并且定义了变量t,没有更改外部的t。
vs
!function(){
var t=1;
function hello(){
console.log(t);
var t=2;
console.log(t);
}
hello(); // undefined 2
console.log(t); // 1
}();
// 这里做出解释:
// 在函数hello内部,有变量提升,其实执行的顺序如下:
// var t;
// console.log(t); // undefined
// t=2;
// console.log(t); // 2
// 而在hello之外,变量t的值仍旧是1,所以输出1
实践三: 实践二的补充,函数提升在代码书写顺序上的不同而带来的问题
!function(){
function hello(){
foo();
function foo(){
console.log('i am foo');
}
}
hello(); // i am foo
}();
// 解释:
// 在函数hello内部,函数式声明,foo提升到了上面,如下:
// function foo(){}
// foo();
// 所以函数能够正常执行
vs
!function(){
function hello(){
foo();
var foo=function(){
console.log('i am foo');
}
}
hello(); // 错误 执行后not a function
}();
// 解释:通过函数字面量的形式来声明函数,在此处是变量提升,得到undefined,因为undefined无法执行,所以会报错,按照下面的顺序来理解:
// var foo;
// foo();
// foo = function(){};
// 所以 就会报错:Uncaught TypeError: foo is not a function
总结:函数提升和变量提升,其实也差不多就这样,可能也会有很多变化形式,但主旨我们都已经说了,我们在写代码的时候,为了让程序更易懂,更容易维护,尽量规避这些问题。