擷取
減少全域變數- 企圖擷取不存在的屬性,會產生undefined
stooge['middle-name'] //undefined
flight.status //undefined
較好的做法 - 給予預設值
var middle = stooge['middle-name'] || "(none)";
var status = flight.status || "unknown"; - 企圖從undefined取值,將丟出TypeError
可利用&&防衛此狀況
flight.equipment //undefined
flight.equipment.model //丟出"TypeError"
flight.equipment && flight.equipment.model //undefined
全域變教會削弱程式的彈性,利用物件包裝
var MYAPP = { };
//利用這個變數保存全域變數
MYAPP.flight = {
airline: "Oceanic",
number:815
};
Reference
JavaScript: The Good Parts - 中譯:JavaScript: 優良部份