先來兩道題。下面這段程式碼執行後 alert 出什麼?
var foo = 1;
function bar() {
if (!foo) {
var foo = 10;
}
alert(foo);
}
bar();
如果答案是 10 讓你吃驚,那麼下一段會讓你更困惑:
var a = 1;
function b() {
a = 10;
return;
function a() {}
}
b();
alert(a);
瀏覽器 alert 出 1。看起來奇怪、危險又令人費解,但它其實是這門語言一個很有表現力的特性。本文用 hoisting 這個詞來描述它。
作用域是新手最容易困惑的部分之一,很多有經驗的工程師也說不清楚。麻煩之處在於 JavaScript 的 scoping 看起來非常像 C 系語言,行為卻截然不同。
#include <stdio.h>
int main() {
int x = 1;
printf("%d, ", x); // 1
if (1) {
int x = 2;
printf("%d, ", x); // 2
}
printf("%d\n", x); // 1
}
輸出 1 2 1,因為 C 系語言有塊級作用域。而在瀏覽器控制台試試:
var x = 1;
console.log(x); // 1
if (true) {
var x = 2;
console.log(x); // 2
}
console.log(x); // 2
輸出 1 2 2。JavaScript 是函數級作用域:只有函數建立新作用域,區塊不會。需要臨時作用域時,用 IIFE 包住即可:
function foo() {
var x = 1;
if (x) {
(function () {
var x = 2;
// some other code
}());
}
// x is still 1.
}
在 JavaScript 中,一個作用域內的名稱有四種來源:
this 和 arguments。function foo() {}。var foo;。函數宣告與變量宣告會被解譯器隱式提升到所屬作用域的最頂端。而語言定義與形參本來就在頂端。
function foo() {
bar();
var x = 1;
}
實際被理解為:
function foo() {
var x;
bar();
x = 1;
}
因此宣告是否被执行並不影響結果,下面兩段等價:
function foo() {
if (false) {
var x = 1;
}
return;
var y = 1;
}
function foo() {
var x, y;
if (false) {
x = 1;
}
return;
y = 1;
}
注意:被提升的只有「宣告」,賦值部分留在原地。函數宣告則連函數體一起提升。而宣告函數有兩種寫法:
function test() {
foo(); // TypeError "foo is not a function"
bar(); // "this will run!"
var foo = function () { // 函數表達式賦值給 foo
alert("this won't run!");
}
function bar() { // 名為 bar 的函數宣告
alert("this will run!");
}
}
test();
最重要的特例是 name resolution order。上面列出的四種來源順序,就是它們的解析優先級。一旦某個名稱已被定義,它不會被同名的其他來源覆蓋——也就是說函數宣告的優先級高於變量宣告,但這只影響「宣告」,賦值依然有效。
幾個例外:
arguments 行為古怪,它似乎在形參之後、函數宣告之前被宣告。所以名為 arguments 的形參會蓋過內建物件,即使值為 undefined。不要拿 arguments 當形參名。this 當標識符使用都會導致語法錯誤,這是好事。函數表達式也可以具名,但它不會變成函數宣告,名稱不會進入作用域,函數體也不會被提升:
foo(); // TypeError "foo is not a function"
bar(); // valid
baz(); // TypeError "baz is not a function"
spam(); // ReferenceError "spam is not defined"
var foo = function () {}; // 匿名函數表達式('foo' 被提升)
function bar() {}; // 函數宣告('bar' 與函數體被提升)
var baz = function spam() {}; // 具名函數表達式(只有 'baz' 被提升)
foo(); // valid
bar(); // valid
baz(); // valid
spam(); // ReferenceError "spam is not defined"
最重要的一條:宣告變量時永遠帶上 var。強烈建議每個作用域只在最頂端寫一個 var,強迫自己這麼做,就永遠不會被提升問題困擾。搭配 JSLint 的 onevar 選項效果更好:
/*jslint onevar: true [...] */
function foo(a, b, c) {
var x = 1,
bar,
baz = "something";
}
直接翻 ECMAScript 規範(section 12.2.2)往往比看二手解讀更清楚:
If the variable statement occurs inside a FunctionDeclaration, the variables are defined with function-local scope in that function... A Block does not define a new execution scope. Only Program and FunctionDeclaration produce a new scope. Variables are initialised to undefined when created. A variable with an Initialiser is assigned the value of its AssignmentExpression when the VariableStatement is executed, not when the variable is created.
希望這篇能解開 JavaScript 中最容易讓人困惑的那部分。若有任何錯誤或遺漏,歡迎指正。