jQuery 這類框架普及之後,很多人寫 JavaScript 都習慣了函數式風格,反而對原生的物件導向機制感到陌生——閉包、原型總是說不清。要搞懂 JavaScript 的物件導向,得先把四種成員類型的行為與可見性分清楚。
掛在 this 上的屬性、以及掛在 prototype 上的方法,都屬於公有成員,外部可以自由存取。
function User(name, age) {
this.name = name; // 公有屬性
this.age = age;
}
User.prototype.getName = function () { // 公有方法
return this.name;
};
var user = new User('fire子海', 26);
console.log(user.getName()); // fire子海
用 var 宣告在函式作用域內的變數與函式,外部完全看不到——這正是閉包提供的隱私。
function User(name, age) {
var name = name; // 私有屬性
var age = age;
function alertAge() { // 私有方法
alert(age);
}
alertAge(age); // 彈出 26
}
var user = new User('fire子海', 26);
// user.age 是 undefined,user.alertAge 也不存在
直接掛在函式(也就是建構子本身)上的成員,不需 new 就能存取,等同 PHP 或 Java 的 static。
function User() {}
User.age = 26; // 靜態屬性
User.myname = 'fire子海';
User.getName = function () { // 靜態方法
return this.myname;
};
console.log(User.getName()); // fire子海
注意這裡刻意用 myname 而非 name——因為 User.name 是函式物件本身的內建屬性(回傳函式名稱),會撞名。
特權方法是「定義在 this 上、但內部能存取私有變數」的方法。它是私有與公有之間的橋梁。
function User(name, age) {
var name = name; // 私有屬性
var age = age;
this.getName = function () { // 特權方法
return name; // 直接取私有變數,不用 this
};
}
var user = new User('fire子海', 26);
console.log(user.getName()); // fire子海
若只需要一組工具函式,不必動用建構子,直接用物件字面量就好:
var user = {
init: function (name, age) {
this.name = name;
this.age = age;
},
getName: function () {
return this.name;
}
};
user.init('fire子海', 26);
console.log(user.getName()); // fire子海
規則可以濃縮成一句:公有方法用 this 取公有與特權成員,但取靜態成員必須透過建構子名稱。而且公有方法看不到私有成員。
function User() {
this.myname = 'fire子海'; // 公有屬性
this.age = 26;
this.do = function () { // 特權方法
return this.myname + ' 學習 js';
};
}
User.eat = function (food) { // 靜態方法
return '晚餐只有' + food;
};
User.prototype.alertAge = function () { // 公有方法
alert(this.age);
};
User.prototype.alertDo = function () {
alert(this.do()); // 特權方法可用 this 呼叫
};
User.prototype.alertEat = function (food) {
alert(User.eat(food)); // 靜態方法必須用建構子名稱
// alert(this.eat(food)) 會出錯:this.eat is not a function
};
var user = new User();
user.alertAge(); // 26
user.alertDo(); // fire子海 學習 js
user.alertEat('方便面'); // 晚餐只有方便面
靜態方法不需實例化即可呼叫;反過來說,實例無法存取靜態成員。
function User() {}
User.age = 26; // 靜態屬性
User.myname = 'fire子海';
User.getName = function () { // 靜態方法
return this.myname;
};
var user = new User();
// console.log(user.getName); // TypeError: user.getName is not a function
user.supper = '方便面';
user.eat = function () {
return '晚餐只有' + this.supper;
};
user.eat(); // 晚餐只有方便面
靜態方法也無法存取公有屬性、公有方法、私有成員、特權方法或原型屬性——因為它執行時根本沒有實例的 this。
function User() {
this.myname = 'fire子海';
this.age = 26;
this.do = function () {
return this.myname + ' 學習 js';
};
}
User.prototype.alertAge = function () { // 公有方法
alert(this.age);
};
User.prototype.sex = '男'; // 原型屬性
User.getName = function () {
return this.myname; // 這裡的 this 是 User,myname 不存在
};
User.getAge = function () {
this.alertAge(); // this.alertAge 不存在
};
User.getDo = function () {
return this.do(); // this.do 不存在
};
// console.log(User.getName()); // undefined
// console.log(User.getDo()); // TypeError: this.do is not a function
// console.log(User.getAge()); // TypeError: this.alertAge is not a function
特權方法最靈活:用 this 取公有成員、用建構子名稱取靜態成員、直接呼叫私有成員。
function User(girlfriend) {
var girlfriend = girlfriend;
function getGirlFriend() { // 私有方法
return '我女朋友' + girlfriend + '是美女!';
}
this.myname = 'fire子海'; // 公有屬性
this.age = 26;
this.do = function () { // 特權方法
return this.myname + ' 學習 js';
};
this.alertAge = function () {
this.changeAge(); // 特權方法呼叫公有方法
alert(this.age);
};
this.alertGirlFriend = function () {
alert(getGirlFriend()); // 直接呼叫私有方法
};
}
User.prototype.changeAge = function () { // 公有方法
this.age = 29;
};
var user = new User('某某');
user.alertAge(); // 29
user.alertGirlFriend(); // 我的女朋友某某是美女!
這是最容易踩坑的地方:私有方法內的 this 不指向實例。因為以「純函式呼叫」的方式執行時,非嚴格模式下的 this 會指向全域物件(window)。
function User(girlfriend) {
var girlfriend = girlfriend;
this.myname = 'fire子海'; // 公有屬性
this.age = 26;
function getGirlFriend() {
// this.myname 這裡的 this 是 window,不是 User 實例
alert(User.eat('泡面')); // 正確做法:用建構子名稱取靜態方法
}
this.do = function () {
return this.myname + ' 學習 js';
};
this.alertAge = function () {
this.changeAge();
alert(this.age);
};
this.alertGirlFriend = function () {
getGirlFriend(); // 純函式呼叫,this 已丟失
};
}
User.eat = function (supper) {
return '晚餐只有' + supper;
};
var user = new User('某某');
user.alertGirlFriend();
把規則整理成表:
最後要補充的是,ES6 的 class 語法與 # 私有欄位已經把這套規則簡化了很多:
class User {
#age; // 真正的私有欄位
constructor(name, age) {
this.name = name; // 公有
this.#age = age; // 私有
}
static myname = 'fire子海'; // 靜態屬性
static getName() { return this.myname; } // 靜態方法
getAge() { // 公有方法
return this.#age;
}
#validate() { // 私有方法
return this.#age > 0;
}
}
const u = new User('fire子海', 26);
u.getAge(); // 26
// u.#age 語法錯誤,真正存取不到
User.getName(); // fire子海
# 前綴的私有欄位是語言層級的保證,不像閉包那樣需要靠 this 指向的微妙規則來維持。理解上面那套傳統規則仍有價值——它能解釋大量既有程式碼的行為,也讓你明白 ES6 究竟替我們省掉了哪些心智負擔。