在一個專案中大量使用 JavaScript 時,工程專案與網站開發有些不同。在我接觸的工程專案中,普遍使用 JS 的情況不夠多,大部分客戶端的工作都交給了服務端,而且使用 JS 時不夠規範,容易造成程式碼難以閱讀、記憶體洩漏等問題。而在網站開發中(尤其是一些大型網站),JS 輸出得非常漂亮、完整,無論使用 jQuery、prototype 框架還是不用框架,都有良好的一套做法。
JS 撰寫最好採用物件導向的方式,用類別方向進行包裝。常見的兩種寫法是閉包與原型。
function Person(firstName, lastName, age) {
// 私有變量:
var _firstName = firstName;
var _lastName = lastName;
// 公共變量:
this.age = age;
// 方法:
this.getName = function() {
return (firstName + " " + lastName);
};
this.SayHello = function() {
alert("Hello, I'm " + firstName + " " + lastName);
};
}
var BillGates = new Person("Bill", "Gates", 53);
// 定義構造函數
function Person(name) {
this.name = name; // 在構造函數中定義成員
}
// 方法定義到構造函數的 prototype 上
Person.prototype.SayHello = function() {
alert("Hello, I'm " + this.name);
};
// 子類構造函數
function Employee(name, salary) {
Person.call(this, name); // 調用上層構造函數
this.salary = salary; // 擴展的成員
}
// 子類構造函數首先需要用上層構造函數來建立 prototype 物件,實現繼承
Employee.prototype = new Person();
// 子類方法也定義到構造函數之上
Employee.prototype.ShowMeTheMoney = function() {
alert(this.name + " $" + this.salary);
};
var BillGates = new Person("Bill Gates");
BillGates.SayHello();
var SteveJobs = new Employee("Steve Jobs", 1234);
SteveJobs.SayHello();
這兩種方法各有優缺點。第一種看起來更像一個類,但每個物件都設定一份方法,頗為浪費,而且資源回收不利;第二種寫法看起來不太漂亮,但效能很好(若使用 prototype 框架,就能兼顧結構與效能)。
就我使用 jQuery 與 prototype 的一點體會:jQuery 使用閉包方式,而 prototype 當然是原型。jQuery 更適合對單個物件操作,prototype 更適合做一些客戶端控制項。就個人而言,我更喜歡在專案中使用 jQuery,而在網站上更關注 prototype。