在 JavaScript 中,若使用 prototype 加入屬性,通常會變成公開成員。這在需要資訊隱藏時並不理想。所幸,也可以建立外部無法直接存取的私有屬性。
在構造函式中用 var 宣告的變數,會成為私有屬性。外部若要存取,必須透過以 this 定義的公共方法,也就是所謂的特權函式。
function Vehicle() {
var wheelCount = 4;
var curbWeightInPounds = 4000;
this.getWheelCount = function() {
return wheelCount;
};
this.setWheelCount = function(count) {
wheelCount = count;
};
}
在這個例子中,wheelCount 與 curbWeightInPounds 都是私有屬性。外部若直接讀取 vehicle.wheelCount,只會得到 undefined,必須透過 getWheelCount 等方法取得。
這種做法能讓物件內部狀態受到保護,也讓對外介面更清楚。對於需要維護狀態的元件,資訊隱藏能降低誤用風險。