變量提升
- demo
var v = "hello world";
(function (){
console.log(v);
var v = "hi";
})() //undefined
//相當于
var v = "hello world";
(function (){
var v;
console.log(v);
v = "hi";
})()
var
的變量提升只是定義提升至最前,變量的賦值不會提升
創(chuàng)建函數(shù)的有兩種方式
- 函數(shù)聲明
function f(){}
function test(){
foo();
function foo(){
console.log("hello");
}
}
test(); //"hello"
- 定義一個變量
var f = function (){}
function test(){
foo();
var foo = function foo(){
console.log("hello");
}
}
test(); // foo is not a function
//相當于
function test(){
var foo;
foo();
foo = function foo(){
console.log("hello");
}
}
test();
- 函數(shù)本身也是一種變量,所以也存在提升,函數(shù)聲明的方式是提升了整個函數(shù),所以可以正確執(zhí)行,定義變量的方式,并沒有提升整個函數(shù),所以會報錯
參考文章推薦
Javascript作用域和變量提升