功能簡單時,所有 JavaScript 都塞在一個檔案裡,寫得飛快;等到需求堆疊、檔案破萬行,才發現自己再也找不到某段邏輯寫在哪。這種痛,很多人都有過。
回頭檢視手上的專案結構,大致可以歸納成兩種思路,各有取捨。
css/ img/ js/ app.js controllers.js directives.js filters.js services.js lib/ partials/ index.html
問題:controller 與 service 一旦變多,js 資料夾立刻 chaos。當然可以繼續往下開 controllers/、services/ 子資料夾,結構確實清楚了些;但 module 數量一多,你也很難一眼判斷某個檔案到底屬於哪個功能。
把共用資源抽到根目錄的 common,每個模組自己擁有一套完整結構:
common/
imgs/
js/
css/
fonts/
modules/
home/
css/
js/ // 需要時可再往下細分
imgs/
index.js // 入口檔
index.html
優勢:新增與移除模組的コスト都很低。要下架一個功能,只需刪掉 modules 下對應的資料夾,再把 routes 裡那條路由拿掉即可,不必全專案翻找殘留引用。
做法:JS 直接寫在 HTML 裡。
優點:改單頁很快,不必擔心牽動其他頁面,適合功能簡單、幾乎沒有複用需求的頁面。
缺點:完全無法複用,程式碼綁死在這頁。
<html>
<body>
<input type="text" name="username" id="username" value="" />
<input type="password" name="password" id="password" value="" />
<script type="text/javascript">
if (document.getElementById("username").value == "") {
alert("用戶名不能為空");
}
if (document.getElementById("password").value == "") {
alert("密碼不能為空");
}
</script>
</body>
</html>
做法:把重複出現的判斷包成函式。
優點:有了初步複用能力,同一段邏輯只需改一處。
缺點:function 一多,又回到「這段到底寫在哪」的老問題。
function check_username() {
if (document.getElementById("username").value == "") {
alert("用戶名不能為空");
}
}
function check_password() {
if (document.getElementById("password").value == "") {
alert("密碼不能為空");
}
}
當 function 多到難以查找,就該按領域分組了。ES5 時代常見兩種寫法:
(1)建構函式:
function register() {
this.check_username = function () {
if (document.getElementById("username").value == "") {
alert("用戶名不能為空");
}
}
this.check_password = function () {
if (document.getElementById("password").value == "") {
alert("密碼不能為空");
}
}
}
new register().check_username(); // 呼叫
(2)物件字面量:
var register = {
check_username: function () {
if (document.getElementById("username").value == "") {
alert("用戶名不能為空");
}
},
check_password: function () {
if (document.getElementById("password").value == "") {
alert("密碼不能為空");
}
}
}
register.check_username(); // 呼叫
物件字面量的語法更輕,不必 new,也天然形成命名空間,是這個階段比較省事的選擇。
參考:〈如何組織好js代碼〉、〈如何組織大型JavaScript應用中的代碼?〉