变量被提升
var x = 10;
function x(){};
console.log(x);// 打印出10
因为变量声明和函数声明会被解释为:
var x;
function x(){};
x = 10;
console.log(x);// 10
函数被提升
声明式函数会自动将声明放在前面并且执行赋值过程,而变量式则是先将声明提升,然后到赋值处再执行赋值。
function test(){
foo();// TypeError "foo is not a function"
bar();// "this will run!"
var foo = function(){
alert("this won't run!");
}
function bar(){// function declaration,given the name 'bar'
alert('this will run !');
}
}
test();
实际上等价于:
function test(){
var foo;
var bar;
bar = function(){
alert("this won't run !");
};
foo();// TypeError "foo is not a function"
bar();// "this will run!"
foo = function(){
alert("this won't run !");
}
}
test();