封裝是面向對象的三大特性之一。本文以「手機類」為例,一步步示範如何用閉包、私有屬性、共有方法與特權方法完成封裝。
var MobilePhone = (function(){
// ...
})();
這裡用來記錄實例化手機的數量:
var MobilePhone = (function(){
var count = 0; // 私有屬性,代表手機數量
})();
每支手機都有顏色、大小、價格屬性。構造函數本身也是一個閉包,因此能存取 count,且只要有理論參照存在,count 就會長期保存在記憶體中:
var MobilePhone = (function(){
var count = 0;
var creatphone = function(color, size, price){
count++;
this._color = color;
this._size = size;
this._price = price;
this.index = count; // 第幾台被建立的手機
};
})();
所有實例都能使用的方法應放在「原型對象」中,原因有三:一是所有實例都能繼承使用;二是若放在構造函數中,每次實例化都會產生一堆重複方法、浪費記憶體;三是透過設定 "constructor": creatphone,可讓被覆寫的原型對象重新與構造函數關聯起來。
var MobilePhone = (function(){
var count = 0;
var creatphone = function(color, size, price){
count++;
this._color = color;
this._size = size;
this._price = price;
this.index = count;
};
creatphone.prototype = {
"constructor": creatphone,
"getColor": function(){ return this._color; },
"setColor": function(color){ this._color = color; },
"getSize": function(){ return "width:" + this._size.width + " height:" + this._size.height; },
"setSize": function(size){ this._size.width = size.width; this._size.height = size.height; },
"getPrice": function(){ return this._price; },
"setPrice": function(price){ this._price = price; }
};
})();
特權方法能存取類的私有變數。這裡我們加一個能讀取「共建立幾台手機」的方法,並回傳構造函數:
var MobilePhone = (function(){
var count = 0;
var creatphone = function(color, size, price){
count++;
this._color = color;
this._size = size;
this._price = price;
this.index = count;
};
creatphone.prototype = {
"constructor": creatphone,
"getColor": function(){ return this._color; },
"setColor": function(color){ this._color = color; },
"getSize": function(){ return "width:" + this._size.width + " height:" + this._size.height; },
"setSize": function(size){ this._size.width = size.width; this._size.height = size.height; },
"getPrice": function(){ return this._price; },
"setPrice": function(price){ this._price = price; }
};
// 特權方法:讀取私有變數 count
creatphone.get_count_index = function(){
return count;
};
return creatphone;
})();
var anycall = new MobilePhone();
var HTC = new MobilePhone();
var Iphone4s = new MobilePhone();
console.log("三星是第:" + anycall.index + "台");
console.log("HTC是第:" + HTC.index + "台");
console.log("Iphone4s是第:" + Iphone4s.index + "台");
console.log("總共造出了" + MobilePhone.get_count_index() + "手機");
console.log(anycall.constructor === MobilePhone); // 原型中的 constructor 是否仍指向 MobilePhone
執行結果全部正確:

透過私有屬性、共有方法與特權方法的搭配,我們就用閉包完成了一個具備封裝特性的手機類,既保護了內部資料,又對外提供了受控的操作接口。