在 JavaScript 中,var a = 1; 與直接寫 a = 1; 是截然不同的:前者宣告的是目前作用域中的區域變數,後者則會產生全域變數。
JavaScript 一個特別之處,在於函式內部可以直接讀取全域變數:
var n = 999;
function f1(){ alert(n); }
f1(); // 999
反過來說,函式外部則無法讀取函式內部的區域變數:
function f1(){ var n = 999; }
alert(n); // 錯誤
var x = '000 ';
document.writeln(x); // 000
a();
function a(){
var x = 'aaa ';
function b(){
document.writeln(x); // undefined(已宣告但尚未賦值)
var x = 'bbb ';
document.writeln(x); // bbb
}
b();
document.writeln(x); // aaa
}
// 輸出:000 undefined bbb aaa
原理:使用變數時,會先從目前函式塊中尋找,找不到再往上一層函式塊找,直到找到為止;若一直到頂層都找不到定義,就會拋出未定義的錯誤。由於 JavaScript 存在變數提升(hoisting),函式內的 x 雖然在賦值前被讀取,卻已宣告,因此得到 undefined。
再看一個例子:
var x = "global";
function f() {
var x = 'f1';
function f2(){
x = 'f2'; // 修改的是 f() 中的 x,而非全域 x
alert(x); // f2
alert(window.x); // global
}
f2();
alert(x); // f2
}
f();
alert(x); // global
// 依序彈出:f2 global f2 global
解釋:f2() 作為內部函式會產生自己的作用域,因此 x='f2' 修改的是外層 f() 中的 x,而非全域變數。
1. 盡量減少全域變數,可將變數封裝進物件中:
var DudeNameSpace = {
name : 'Jeffrey',
lastName : 'Way',
doSomething : function() { /* ... */ }
};
console.log(DudeNameSpace.name); // Jeffrey
正如 Douglas Crockford 所說,把雜亂的全域足跡都歸於單一物件之下,能顯著降低與其他程式或 JS 函式庫衝突的機率。
2. 用逗號合併宣告,讓程式碼更簡潔:
var someItem = 'some string',
anotherItem = 'another string',
oneMoreItem = 'one more string';