萬盛學電腦網

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

快速掌握 JavaScript 面向對象編程:從對象字面量到構造函數與原型

為什麼需要面向對象?

亂糟糟的屬性、方法、巢狀循環讓代碼只有上帝能讀懂。OO 能帶來:

  • 邏輯封裝、職責單一
  • 代碼復用、易擴展
  • 團隊並行開發、易維護

第一步:對象字面量 —— 單例快速建模

// 建立空對象
const bill = {};

// 動態添加屬性/方法
bill.name = "Bill E Goat";
bill.sound = function() { console.log("bahhh!"); };

// 一次性定義(推薦)
const bill = {
    name: "Bill E Goat",
    sound() { console.log("bahhh!"); } // ES6 方法簡寫
};

// 訪問
bill.name;        // "Bill E Goat"
bill.sound();     // "bahhh!"
bill["name"];     // 非合法標識符屬性名必須用括號

this 陷阱初體驗

bill.sayName = function() {
    console.log("Hello " + this.name);
};
bill.sayName(); // "Hello Bill E Goat"

const sayName = bill.sayName;
sayName(); // "Hello undefined" —— this 丟失!指向 window/undefined

教訓:方法被提取為獨立函數調用時,this 指向改變。

第二步:構造函數 —— 批量產出同結構實例

function Game(title) {
    this.title = typeof title !== "undefined" ? title : "";
}

// 建立實例
const zelda = new Game("Legend of Zelda");
const smb = new Game("Super Mario Brothers");

zelda.title; // "Legend of Zelda"
smb.title;   // "Super Mario Brothers"

// 動態添加實例方法
zelda.loveTitle = function() {
    console.log("I love " + this.title);
};
zelda.loveTitle(); // "I love Legend of Zelda"

構造函數執行流程

  1. 建立新空物件 {}
  2. this 指向新物件
  3. 執行函數體內代碼
  4. 隱式返回 this(除非显式返回物件)

第三步:原型 —— 方法共享、記憶體優化

Game.prototype.heartIt = function() {
    console.log("I heart " + this.title);
};

zelda.heartIt(); // "I heart Legend of Zelda"
smb.heartIt();   // "I heart Super Mario Brothers"

// 原型鏈查找:zelda → Game.prototype → Object.prototype → null

所有實例共享同一個 heartIt 函數,節省記憶體。

第四步:原型繼承 —— 擴展功能

function RPG(title, level) {
    Game.call(this, title); // 繼承屬性
    this.level = level;
}

// 繼承原型方法
RPG.prototype = Object.create(Game.prototype);
RPG.prototype.constructor = RPG; // 修正 constructor

RPG.prototype.grind = function() {
    this.level++;
    console.log(this.title + " level up to " + this.level);
};

const ff7 = new RPG("Final Fantasy VII", 1);
ff7.heartIt(); // 繼承自 Game.prototype
ff7.grind();   // "Final Fantasy VII level up to 2"

第五步:ES6 Class 語法糖(現代標準寫法)

class Game {
    constructor(title = "") {
        this.title = title;
    }
    heartIt() {
        console.log("I heart " + this.title);
    }
}

class RPG extends Game {
    constructor(title, level) {
        super(title); // 必須先呼叫 super()
        this.level = level;
    }
    grind() {
        this.level++;
        console.log(`${this.title} level up to ${this.level}`);
    }
}

const eldenRing = new RPG("Elden Ring", 1);
eldenRing.heartIt(); // "I heart Elden Ring"
eldenRing.grind();   // "Elden Ring level up to 2"

Class 底層仍是原型繼承,但語法更清晰、不易出錯。

最佳實踐清單

  1. 優先使用 class / extends(ES6+)
  2. 方法定義在 prototype/類體中,不在構造函數內
  3. 慎用 this 閉包陷阱,必要時用箭頭函數綁定:this.handleClick = () => { ... }
  4. 組合優於繼承:const user = { ...authMixin, ...logMixin }
  5. 不可變數據:Object.freeze()、const、readonly (TS)
copyright © 萬盛學電腦網 all rights reserved