變量被提升
var x = 10;
function x(){};
console.log(x);// 打印出10
因?yàn)樽兞柯暶骱秃瘮?shù)聲明會(huì)被解釋為:
var x;
function x(){};
x = 10;
console.log(x);// 10
函數(shù)被提升
聲明式函數(shù)會(huì)自動(dòng)將聲明放在前面并且執(zhí)行賦值過程,而變量式則是先將聲明提升,然后到賦值處再執(zhí)行賦值。
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();
實(shí)際上等價(jià)于:
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();