這份筆記整理了 JavaScript 物件導向程式設計的核心概念,包含類別建立方式、多種繼承模式、靜態成員、記憶體管理等進階主題,適合有基礎的開發者深入理解 JS 物件機制。
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); // 正常運作
特點:方法定義在外部,透過參考共享,節省記憶體,但封裝性較差。
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) {
A.call(this, x); // 或 A.apply(this, [x])
this.y = y;
}
instanceof 檢測失敗,必須用建構函式模式function A() {}
A.prototype.x = 1;
function B() {}
B.prototype = new A(); // 原型指向父實例
B.prototype.y = 2;
instanceof 正常運作,方法共享節省記憶體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 繼承,方法用原型鏈共享。
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 = null; // 解除參考,等待 GC 回收
var v = new Function("arg1", "arg2", "document.write(arg1 + arg2);");
v(1, 2); // 輸出 3
function callback(func, arg) { func(arg); }
function fun(arg) { document.write(arg); }
var func = new Function("arg", "fun(arg);");
callback(func, "sb");
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!");
}
}
fun(1); // 1
fun(1, 2); // 3
function fun() {
var v = 1;
function fun2() {
++v;
document.write(v + "<br>");
return v;
}
return fun2;
}
var func = fun();
func(); // 2
func(); // 3
func(); // 4
透過閉包保存外部函式的區域變數,模擬類靜態變數行為。
JavaScript 雖無傳統類別語法,但透過原型鏈、建構函式、閉包等機制,能靈活實現物件導向所有核心特性。實務開發建議採用混合模式,並善用 ES6 class 語法糖提升可維護性。