這份筆記整理幾個 JavaScript 的進階主題:如何定義類、實作繼承、模擬靜態成員、釋放物件、使用函式物件與回呼,以及用閉包做出「有靜態變數的函式」。
function sth(a) { // 建構函式
this.a = a;
this.fun = output; // 成員函式
}
function output(a, b, c) {
document.write(this.a);
}
// 呼叫
var s = new sth(250);
s.fun(1, 2, 3);
output(1, 2, 3); // 若 output 定義在 sth 之前,這裡會出錯
注意最後那行:因為函式表達式不若函式宣告會被提升,指派時機錯了就會拿到 undefined。
function sth(a) {
this.a = a;
this.output = function() {
document.write(this.a);
}
}
var s = new sth(2);
s.output(); // 輸出 2
function A(x) {
this.x = x;
}
function B(x, y) {
// 寫法 1
this.construct = A;
this.construct(x);
delete this.construct;
// 寫法 2
A.call(this, x);
// 寫法 3
A.apply(this, new Array(x)); // 亦可 A.apply(this, arguments),但參數順序必須正確
this.y = y;
this.print = function() {
document.write("x = ", x, ", y = ", y);
}
}
var b = new B(1, 2);
b.print();
alert(B instanceof A); // 輸出 false
優點:可以實現多繼承(多呼叫幾次 call 即可)。
缺點:必須以建構函式方式使用;instanceof 判定此種繼承結果為 false,因為原型鏈並未串接。
function A() {}
A.prototype.x = 1;
function B() {}
B.prototype = new A(); // 不能帶參數!
B.prototype.y = 2;
B.prototype.print = function() {
document.write(this.x, ", ", this.y, "<br>");
};
var b = new B();
b.print();
document.write(b instanceof A); // 輸出 true
缺點:不能實現多繼承;建構函式不能帶參數。
兩者一起用:用 call 處理實例屬性的初始化,用原型鏈處理方法共享。
function A(x) {
this.x = x;
}
A.prototype.printx = function() {
document.write(this.x, "<br>");
};
function B(x, y) {
A.call(this, x);
this.y = y;
}
B.prototype = new A(); // 不能帶參數
B.prototype.printxy = function() {
document.write(this.x, ", ", this.y, "<br>");
};
var b = new B(1, 2);
b.printx(); // 輸出 1
b.printxy(); // 輸出 1, 2
document.write(b instanceof A); // 輸出 true
這個組合兼得兩邊的長處:屬性靠 call 正確初始化,方法靠原型共享而不必每個實例各複製一份(用方法一時,每個實例都會帶一份 print 函式,記憶體上很浪費)。
function sth(a) {
this.a = a;
}
sth.fun = function(s) {
document.write(s.a);
};
var s = new sth(2);
sth.fun(s); // 輸出 2
直接掛在建構函式上的屬性,不屬於任何實例,呼叫時得自己把要操作的物件傳進去。
var obj = new Object; // obj 是引用 obj = null; // 取消引用,會自動進行垃圾回收
若需要徹底釋放某個物件,必須把它所有的引用都設為 null。這在大量建立 DOM 節點或大陣列時才會有明顯意義;一般情況下交給 GC 即可,不必手動處理。
var v = new Function("arg1", "arg2", "document.write(arg1 + arg2);");
v(1, 2); // 輸出 3
前面幾個參數是形參名稱,最後一個是函式主體。這種寫法的本質與 eval 相同——把字串當程式碼執行——因此效能較差,也不利於工具靜態分析。除了極少數動態生成程式碼的場景,不建議使用。
function callback(func, arg) {
func(arg);
}
function fun(arg) {
document.write(arg);
}
// callback(func, "sb"); 這種寫法不行——傳進去的是執行結果而非函式
var func = new Function("arg", "fun(arg);");
callback(func, "sb");
關鍵觀念:函式名稱後面加括號是「呼叫」,不加才是「函式本身」。要傳函式當參數,就別加括號:
callback(fun, "sb"); // 直接傳函式名稱,正確且簡單
JavaScript 沒有真正的重載(同名函式只會保留最後一個定義),但可以用 arguments 模擬:
function fun() {
switch (arguments.length) {
case 1:
document.write(arguments[0]);
break;
case 2:
document.write(arguments[0] + arguments[1]);
break;
default:
document.write("ERROR!");
break;
}
}
fun(1);
fun(1, 2);
ES6 之後有更清楚的寫法——用參數預設值與 rest 參數取代 arguments:
function fun(a, b) {
if (b === undefined) return a;
return a + b;
}
函式的區域變數在執行完畢後就該消失,但閉包能讓它存活下來,於是就形成了「靜態變數」的效果:
function fun() {
var v = 1;
function fun2() {
++v;
document.write(v);
document.write("<br>");
return v;
}
return fun2;
}
var func = fun();
func(); // 輸出 2
func(); // 輸出 3
func(); // 輸出 4
原理是這樣的:fun() 執行完後,v 並沒有被回收,因為回傳的 fun2 仍持有對它的引用。每次呼叫 func() 都在同一個 v 上累加,行為就等同於靜態變數。
這個技巧最實用的應用是資訊隱藏——用 IIFE 建立私有狀態,只暴露需要的介面,也就是「揭示模樣」(revealing module)模式:
var counter = (function () {
var count = 0; // 私有,外部無法直接存取
return {
increment: function(){ return ++count; },
get: function(){ return count; }
};
})();
counter.increment(); // 1
counter.increment(); // 2
counter.get(); // 2
// counter.count 是 undefined
這份筆記中的技巧在 ES5 時代是必要的,今天則多數有了語法層級的直接支援:
· 類別與繼承 → class / extends / super,本質仍是 prototype,但可讀性大幅提升
· 私有成員 → #privateField 原生私有欄位
· 回呼傳遞 → 直接傳函式名稱;非同步流程改用 Promise / async-await
· 函式重載 → 參數預設值、rest 參數、解構賦值
· 靜態變數與資訊隱藏 → 模組(import / export)中的模組層級變數
讀懂上面這些「繞路寫法」的價值在於:它解釋了那些新語法背後到底在做什麼。例如知道閉包讓變數存活,才明白為什麼 React 的 useEffect 會有「捕獲過期 state」的問題;知道原型鏈,才能解釋 class 為何不能像 Java 那樣真的隱藏實作。這些才是除錯時真正用得上的部分。