作用域問題
JavaScript語言的作用域僅存在于函數(shù)范圍中掠抬。這是必須要牢記的一點(diǎn),還有一點(diǎn)重要的就是作用域的提升規(guī)則校哎。
作用域問題
JS最容易出現(xiàn)混淆的就是作用域的情況两波。對于JavaScript而言,它的作用域是函數(shù)域闷哆,比如if條件語句腰奋,就不算一個(gè)獨(dú)立的作用域:
var x = 1;
console.log(x); // 1
if (true) {
var x = 2;
console.log(x); // 2
}
console.log(x); // 2
在JavaScript中,可以通過立即執(zhí)行函數(shù)創(chuàng)建臨時(shí)作用域:
function foo() {
var x = 1;
if (x) {
(function () {
var x = 2;
// some other code
}());
}
// x is still 1.
}
作用域鏈問題
函數(shù)會(huì)在當(dāng)前作用域?qū)ふ宜淖兞勘д绻麤]有就在上一級尋找劣坊,一直找到最外層
作用域提升
變量被提升
對JavaScript解釋器而言,所有的函數(shù)和變量聲明都會(huì)被提升到最前面, 并且變量聲明永遠(yuǎn)在前面屈留,賦值在聲明過程之后局冰。比如:
var x = 10;
function x(){};
console.log(x); // 10
實(shí)際上被解釋為:
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 () { // function expression assigned to local variable 'foo'
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 () { // function declaration, given the name 'bar'
alert("this will run!");
}
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
foo = function () { // function expression assigned to local variable 'foo'
alert("this won't run!");
}
}
test();
主要注意的地方:帶有命名的函數(shù)變量式聲明勇蝙,是不會(huì)提升到作用域范圍內(nèi)的沫勿,比如:
var baz = function spam() {};
baz(); // vaild
spam(); // ReferenceError "spam is not defined"