JavaScript 沒有原生的區塊作用域(ES6 之前),也沒有真正的 private 修飾符,但它提供了幾個等效手法。以下依序說明塊級作用域、私有變數與模組模式。
1. 塊級作用域(私有作用域)
最常見的用法是包在全域作用域中的立即執行函式,藉此避免往全域塞入過多的變數與函式。
(function(count){
for(var i = 0; i < count; i++){
console.log(i); // 0、1、2、3、4
}
console.log(i); // 5,i 只活在這個函式裡,不會污染全域
})(5);
它也很適合包一段自成一體的邏輯:
(function(){
var now = new Date();
if(now.getMonth() == 0 && now.getDate() == 1){
console.log("新年快樂");
} else {
console.log("盡情期待");
}
})();
2. 私有變數
任何定義在函式內部的變數,外部都無法直接存取,因此可以視為私有變數。而能夠讀寫這些私有資料的公開方法,稱為特權方法。
2.1 在建構函式中定義特權方法
function Person(name){
this.getName = function(){ return name; };
this.setName = function(value){ name = value; };
}
var person1 = new Person("Jason");
console.log(person1.getName()); // Jason
person1.setName("gray");
console.log(person1.getName()); // gray
var person2 = new Person("Michael");
console.log(person1.getName()); // gray
console.log(person2.getName()); // Michael
person2.setName('Alex');
console.log(person1.getName()); // gray
console.log(person2.getName()); // Alex
每個实例各自保有獨立的 name,互不干擾。缺點也很明顯:每建立一個實例,就會重新產生一整組方法,造成記憶體浪費。
2.2 用靜態私有變數實作特權方法
改寫策略是:在私有作用域中先宣告私有變數與函式,再定義建構函式及其公開方法(掛在 prototype 上)。
(function(){
// 私有變數
var name = "";
Person = function(value){
name = value;
};
// 特權方法掛在原型上,所有實例共享
Person.prototype.getName = function(){
return name;
};
Person.prototype.setName = function(value){
name = value;
};
})();
var person1 = new Person("Jason");
console.log(person1.getName()); // Jason
person1.setName("gray");
console.log(person1.getName()); // gray
var person2 = new Person("Michael");
console.log(person1.getName()); // Michael ← 注意,name 是共用的
console.log(person2.getName()); // Michael
person2.setName('Alex');
console.log(person1.getName()); // Alex
console.log(person2.getName()); // Alex
這裡要特別留意差異:因為 name 變成了靜態私有變數,所有實例共享同一份資料。person1 改的值,person2 也看得到。這是效能與資料隔離之間的取捨。
3. 模組模式
模組模式的本質,是為單例(singleton)加上私有變數與特權方法。當你需要建立一個物件、用某些資料初始化它,同時又要對外公開能操作這些資料的方法時,這個模式就很合適。
var application = function(){
// 私有變數與函式
var components = [];
// 初始化
components.push(new BaseComponent());
// 公開介面
return {
getComponentCount: function(){
return components.length;
},
registerComponent: function(component){
if(typeof component == "object"){
components.push(component);
}
}
};
}();
外部只能透過 getComponentCount 與 registerComponent 兩個方法與 components 互動,陣列本身則被妥善藏了起來。這個思路,正是後來 AMD、CommonJS 乃至 ES6 模組化設計的前身。
以上就是這三個概念的整理,希望對你的理解有幫助。