用 IIFE(立即執行函數表達式)包住建構函式,是 JavaScript 早期實作「類」最完整的一種寫法。它能同時做到私有屬性、私有方法、特權方法與靜態成員——這些在 ES6 之前只能靠閉包湊出來。
<script type="text/javascript">
var Book = (function () {
// 私有靜態屬性
var numOfBooks = 0;
// 私有靜態方法
function checkIsbn(isbn) {
if (isbn == undefined || typeof isbn != 'string') {
return false;
}
return true;
}
// 回傳建構函式
return function (newIsbn, newTitle, newAuthor) {
// 私有屬性
var isbn, title, author;
// 特權方法:可以存取上面的私有屬性
this.getIsbn = function () { return isbn; };
this.setIsbn = function (newIsbn) {
if (!checkIsbn(newIsbn)) throw new Error('Book: Invalid ISBN.');
isbn = newIsbn;
};
this.getTitle = function () { return title; };
this.setTitle = function (newTitle) {
title = newTitle || 'No title specified';
};
this.getAuthor = function () { return author; };
this.setAuthor = function (newAuthor) {
author = newAuthor || 'No author specified';
};
// 控制實例數量
numOfBooks++;
if (numOfBooks > 5) {
throw new Error('Book: Only 5 instances of Book can be created.');
}
this.setIsbn(newIsbn);
this.setTitle(newTitle);
this.setAuthor(newAuthor);
};
})();
// 公有靜態方法
Book.convertToTitleCase = function (inputString) {
alert('convertToTitleCase');
};
// 公有非特權方法
Book.prototype = {
display: function () {
alert("isbn:" + this.getIsbn() + " title:" + this.getTitle() + " author:" + this.getAuthor());
}
};
// var theHobbit = new Book(123, '', 'J. R. R. Tolkein'); // 非字串,拋出異常
var theHobbit = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit.display();
// theHobbit.convertToTitleCase(); // TypeError:靜態方法不能用實例呼叫
Book.convertToTitleCase(); // 靜態方法要用類別名稱呼叫
var theHobbit2 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit2.display();
var theHobbit3 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit3.display();
var theHobbit4 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit4.display();
var theHobbit5 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
theHobbit5.display();
var theHobbit6 = new Book('1990-78sd-1092', '', 'J. R. R. Tolkein');
// Uncaught Error: Book: Only 5 instances of Book can be created.
</script>
私有靜態屬性(numOfBooks)與私有靜態方法(checkIsbn)宣告在 IIFE 最外層,被閉包保存。外部完全無法存取,但返回的建構函式內部可以讀寫,因此所有實例共用同一個計數器——這正是「靜態」的意義。
私有屬性(isbn、title、author)宣告在建構函式內,每次 new 都會重新產生一份,外部同樣無法直接存取。
特權方法(this.getIsbn 等)指派在 this 上,因此每個實例都有一份。它們之所以「特權」,是因為處在建構函式的閉包裡,能讀寫那些私有屬性。
公有方法(Book.prototype.display)掛在原型上,所有實例共用一份。注意它只能透過特權方法取得資料,因為它不在私有屬性的閉包內。
特權方法寫在 this 上,代表每 new 一個 Book 就會重新建立四組函式。實例一多,記憶體與效能的負擔跟著上升。經典寫法是「只在建構函式第一次執行時建立特權方法,之後直接沿用」:
var Book = (function () {
var numOfBooks = 0;
function checkIsbn(isbn) { /* ... */ }
return function (newIsbn, newTitle, newAuthor) {
// 只在第一次建立
if (!Book.prototype._initialized) {
// 這裡無法直接存取 isbn,需改用 WeakMap 保存私有狀態
Book.prototype._initialized = true;
}
// ...
};
})();
而 ES6 之後,同樣的需求用 Symbol 或 WeakMap 會乾淨得多:
const ISBN = Symbol('isbn');
class Book {
constructor(isbn, title, author) {
this[ISBN] = isbn;
this.title = title || 'No title specified';
this.author = author || 'No author specified';
}
get isbn() { return this[ISBN]; }
display() {
console.log(`isbn:${this.isbn} title:${this.title} author:${this.author}`);
}
}
用 Symbol 作為 key,外部拿不到這個識別符就無法存取,私有性接近真正的 private;而方法定義在 class body 裡,本來就只存在一份於 prototype 上,不必再擔心重複建立的問題。(若要更嚴格的私有性,ES2022 的 #isbn 私有欄位語法可以直接寫 this.#isbn。)
尽管如此,這套 IIFE 模式很值得讀懂。它清楚展示了閉包如何被用來模擬語言本身沒有的機制,而理解這件事,才能明白 ES6 的 class 到底在背後做了什麼。
以上就是這篇的全部內容,希望對你的 JavaScript 開發有幫助。