萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 進階物件導向筆記:類別、繼承與設計模式

這份筆記整理了 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

特點:每個實例擁有獨立方法副本,封裝性好,但記憶體佔用較大。

二、繼承實現的三種主流方案

方案一:建構函式借用(call/apply)

function A(x) { this.x = x; }
function B(x, y) {
    A.call(this, x); // 或 A.apply(this, [x])
    this.y = y;
}
  • 優點:支援多重繼承(多次呼叫 call),可傳遞參數給父建構函式
  • 缺點: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 回收

Function 建構函式動態建立函式

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 語法糖提升可維護性。

copyright © 萬盛學電腦網 all rights reserved