面試或與同行交流時常會聽到這樣的說法:在 JS 中定義構造函數的方法時,最好定義到 prototype 上,因為這樣所有實例持有的方法都指向同一個函數索引,可以節省記憶體。
這個結論沒錯,但要注意:達到同樣效果的方式並不只 prototype 這一種。
把方法以獨立函數的形式定義在構造函數外部,再在構造函數中透過 this.method = method 掛上去。這樣產生的實例,其方法同樣是指向同一個函數的索引。
(function () {
function Constractor() {
this.method1 = method1;
this.method2 = method2;
}
function method1() { }
function method2() { }
})();
(function () {
function Constractor() { }
Constactor.prototype = {
method1: function () { },
method2: function () { }
};
// 或者逐個掛上:
// Constactor.prototype.method1 = function () { };
// Constactor.prototype.method2 = function () { };
})();
兩種寫法的記憶體表現相同,差異在別的地方:
1. instanceof 的行為。寫法一把方法掛在實例上,用 instanceof 判斷繼承關係時就不準了,因為原型鏈上沒有這些成員。這也是 prototype 寫法更主流的原因之一。
2. 覆寫整塊 prototype 會斷開 constructor 指向。像寫法二那樣直接賦值 prototype = {...},預設的 constructor 屬性就跑到新物件上去了,需要的話要自己補回來。
3. 可讀性與維護性。prototype 寫法把「資料」與「行為」分開陳列,方法列表集中在一處,成員一多時更好維護。
結論:兩種方式在記憶體上等效,但從繼承判斷、語意清晰度與團隊慣例來看,把方法掛到 prototype 仍然是首選。