1 個程式範例,快速學習 JavaScript 物件導向語法

當深入 JavaScript 的核心時,傳統的物件導向編程(OOP)技術顯得非常重要。這種編程風格不僅為代碼提供了清晰的結構,而且還促進了模組化和重用,這對於大型和復雜的應用程序開發尤為關鍵。

本篇文章中,將透過一個全面的範例,一步步探討 JavaScript 中傳統物件導向編程的關鍵概念,包括類別的定義、公共和私有屬性的聲明、構造函數、方法的使用,以及類別的繼承等。這將幫助深入理解 JavaScript 中的 OOP,並將這些知識應用於編程實踐中。

OOP 語法範例:

// 定義一個類別 (Define a Class)
// 類別是JavaScript中用於創建對象的模板。它封裝了相關的屬性和方法。
class Car {
    // 公共屬性 (Declare a Public Property)
    // 公共屬性可以在類別實例的任何地方被訪問和修改。
    color;

    // 私有屬性 (Declare a Private Property)
    // 私有屬性僅在定義它們的類內部可訪問,外部無法直接訪問。
    #brand;

    // 構造函數 (Declare Constructor)
    // 構造函數是在創建類實例時自動調用的特殊方法,用於初始化類的屬性。
    constructor(brand, color) {
        this.#brand = brand;
        this.color = color;
    }

    // 公共方法 (Declare a Public Method)
    // 公共方法可以被類實例及繼承該類的其他類的實例調用。
    displayInfo() {
        console.log(`This is a ${this.color} car.`);
    }

    // 私有方法 (Declare a Private Method)
    // 私有方法僅能在定義它的類內部被調用,對外部是不可見的。
    #privateMethod() {
        return `Brand is ${this.#brand}`;
    }

    // Getter和Setter
    // Getter和Setter用於對類的私有屬性進行安全的訪問和更新。
    get brand() {
        return this.#privateMethod();
    }

    set brand(newBrand) {
        this.#brand = newBrand;
    }

    // 靜態方法和屬性 (Static Methods and Fields)
    // 靜態方法和屬性屬於類本身,而不是類的任何特定實例。
    static numberOfWheels = 4;

    static carDescription() {
        return `Cars usually have ${this.numberOfWheels} wheels.`;
    }
}

// 擴展一個類別 (Extend a Class)
// 使用'extends'關鍵字創建一個新類,繼承另一個類的屬性和方法。
class ElectricCar extends Car {
    constructor(brand, color, batteryLife) {
        super(brand, color); // 調用父類構造函數
        this.batteryLife = batteryLife;
    }

    // 覆寫方法
    displayInfo() {
        console.log(`This is a ${this.color} electric car with a battery life of ${this.batteryLife} hours.`);
    }
}

// 創建一個實例 (Create an Instance)
// 使用'new'關鍵字和類名創建該類的一個新實例。
const myCar = new ElectricCar('Tesla', 'red', 24);

// 調用函數 (Call a Function)
// 通過類實例調用在類中定義的方法。
myCar.displayInfo(); // This is a red electric car with a battery life of 24 hours.

// 點表示法 vs 括號表示法 (Dot vs Bracket Notation)
// 使用點表示法或括號表示法訪問對象的屬性。點表示法更直觀,而括號表示法在屬性名為變量時很有用。
console.log(myCar.color);    // red (點表示法)
console.log(myCar['color']); // red (括號表示法)

這個範例通過注釋解釋了JavaScript 中的關鍵物件導向概念,包括如何定義類別、聲明屬性和方法、創建和使用實例,以及如何實現繼承和多態性。這有助於更好地理解和掌握JavaScript的物件導向特性。

5 thoughts on “1 個程式範例,快速學習 JavaScript 物件導向語法

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *