在 JavaScript 的物件導向設計中,方法的可見性是一個很基礎但也很重要的主題。它牽涉到物件屬性的封裝、原型、建構函數、閉包,以及立即執行函數表達式等概念。
公有方法是指可以在物件外部被呼叫的方法。無論是物件字面值、建構函數,還是原型上定義的方法,只要外部可以存取,都屬於公有方法。
const person = {
name: '小明',
getName() {
return this.name;
}
};
console.log(person.getName());
若使用建構函數與原型,也可以定義公有方法:
function Person(name) {
this.name = name;
}
Person.prototype.getName = function () {
return this.name;
};
私有方法是指外部無法直接存取的方法;特權方法則是指有權限存取內部私有資料的公有方法。這兩個概念通常一起討論,因為它們都與封裝有關。
在物件中,可以透過立即執行函數表達式建立私有狀態,也就是所謂的模組模式:
const restaurant = (function () {
let total = 10;
function buyFood() {
total -= 1;
}
return {
name: 'McDonald',
buy: buyFood,
getTotal() {
return total;
}
};
})();
restaurant.buy();
console.log(restaurant.getTotal());
在建構函數中,也可以直接在函數內部定義私有變數與特權方法:
function Restaurant(name) {
let total = 10;
this.name = name;
this.buy = function () {
total -= 1;
};
this.getTotal = function () {
return total;
};
}
需要注意的是,原型上的方法無法直接存取建構函數內部的私有變數,因此若有多個方法需要存取私有資料,通常會透過特權方法或閉包來處理。
模組模式適合建立一次性的私有狀態;建構函數則適合建立多個實例。將兩者結合,可以兼顧初始化資料與原型方法的優勢:
const Restaurant = (function () {
let total = 10;
function buyFood() {
total -= 1;
}
function InnerRestaurant(name) {
this.name = name;
this.getTotal = function () {
return total;
};
}
InnerRestaurant.prototype.buy = function () {
buyFood();
};
InnerRestaurant.prototype.getName = function () {
return this.name;
};
return InnerRestaurant;
})();
const mcd = new Restaurant('McDonald');
mcd.buy();
console.log(mcd.getTotal());
現代 JavaScript 也支援以 # 符號定義私有欄位,讓封裝語法更直覺:
class Counter {
#count = 0;
increment() {
this.#count += 1;
}
get value() {
return this.#count;
}
}