萬盛學電腦網

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

JavaScript 構造函數與原型模擬 C# 類完整指南

核心模式:構造函數 + 原型

// 1. 構造函數:定義實例屬性
function Person(name, age) {
    this.name = name;
    this.age = age;
}

// 2. 原型:定義共享方法/屬性
Person.prototype = {
    constructor: Person, // 修正 constructor 指向
    getName: function() { return this.name; },
    getAge: function() { return this.age; },
    // 共享屬性(慎用,引用類型會被所有實例共享)
    // skills: [] // 危險!所有實例共用同一數組
};

// 3. 實例化
var p1 = new Person('Alice', 25);
var p2 = new Person('Bob', 30);

console.log(p1.getName()); // "Alice"
console.log(p2.getAge());  // 30
console.log(p1.getName === p2.getName); // true (共享同一函數)

原型鏈機制圖解


p1 ──────► Person.prototype ──────► Object.prototype ──────► null
  │            │
  │            ├─ getName()
  │            ├─ getAge()
  │            └─ constructor: Person
  │
  ├─ name: "Alice"
  └─ age: 25

動態修改原型的影響

Person.prototype.sex = '男'; // 為所有實例添加默認屬性

var p3 = new Person('Charlie', 28);
console.log(p3.sex); // "男" (來自原型)

p3.sex = '保密'; // 實例添加同名屬性,遮蔽原型
console.log(p3.sex); // "保密"

delete p3.sex; // 刪除實例屬性
console.log(p3.sex); // "男" (恢復讀取原型)

繼承實現:寄生組合式繼承(最佳實踐)

function Animal(name) {
    this.name = name;
}
Animal.prototype.say = function() { console.log(this.name + ' makes sound'); };

function Dog(name, breed) {
    Animal.call(this, name); // 繼承實例屬性
    this.breed = breed;
}

// 關鍵:創建中間原型,避免調用 Animal 構造函數
Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog; // 修正 constructor

Dog.prototype.bark = function() { console.log(this.name + ' barks'); };

var dog = new Dog('Buddy', 'Golden');
dog.say();  // "Buddy makes sound" (來自 Animal.prototype)
dog.bark(); // "Buddy barks" (來自 Dog.prototype)
console.log(dog instanceof Dog, dog instanceof Animal); // true true

ES6 Class 語法糖(編譯後本質相同)


class Person {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    getName() { return this.name; }
    getAge() { return this.age; }
    static species = 'Human'; // 靜態屬性
}

class Student extends Person {
    constructor(name, age, grade) {
        super(name, age); // 必須先調用 super()
        this.grade = grade;
    }
    study() { console.log(this.name + ' studying'); }
}

const s = new Student('Tom', 20, 'Senior');
console.log(s.getName()); // "Tom"
s.study();                // "Tom studying"

私有成員模擬方案

方案實現優缺點
閉包 (ES5) 構造函數內 var 私有變量,特權方法訪問 真私有、每實例獨立函數副本(內存開銷)
Symbol 唯一鍵 const _name = Symbol(); this[_name] = name; 非真私有(可遍歷 Symbol),但避免意外訪問
WeakMap const _data = new WeakMap(); _data.set(this, {name}); 真私有、無內存洩漏、需 ES6
#私有字段 (ES2022) class { #name; constructor(n){this.#name=n;} } 原生真私有、語法清晰、現代瀏覽器全支援

ES2022 私有字段實戰


class BankAccount {
    #balance = 0; // 私有字段
    #transactions = []; // 私有數組

    constructor(owner) {
        this.owner = owner; // 公共屬性
    }

    deposit(amount) {
        if (amount <= 0) throw new Error('金額需大於0');
        this.#balance += amount;
        this.#transactions.push({type: 'deposit', amount, time: Date.now()});
    }

    withdraw(amount) {
        if (amount > this.#balance) throw new Error('餘額不足');
        this.#balance -= amount;
        this.#transactions.push({type: 'withdraw', amount, time: Date.now()});
    }

    getBalance() { return this.#balance; }

    getStatement() {
        return this.#transactions.map(t => `${t.type}: ${t.amount}`);
    }
}

const acc = new BankAccount('Alice');
acc.deposit(1000);
acc.withdraw(200);
console.log(acc.getBalance()); // 800
// acc.#balance; // SyntaxError: Private field '#balance' must be declared in an enclosing class

靜態成員與繼承


class Config {
    static API_URL = 'https://api.example.com';
    static getHeaders() { return { 'Content-Type': 'application/json' }; }
}

class AdminConfig extends Config {
    static ADMIN_TOKEN = 'secret';
}

// 子類繼承父類靜態成員
console.log(AdminConfig.API_URL); // "https://api.example.com"
console.log(AdminConfig.getHeaders()); // { 'Content-Type': 'application/json' }

最佳實踐總結

  1. 優先使用 ES6 Class:語法清晰、原生支援繼承、私有字段、靜態成員
  2. 方法放原型,屬性放實例:節省內存、體現共享/獨有語義
  3. 避免在原型放引用類型默認值:prototype.items = [] 導致所有實例共享
  4. 修正 constructor:手動修改原型時記得 Constructor.prototype.constructor = Constructor
  5. 組合優於繼承:混入、裝飾器、策略模式替代深層繼承樹
  6. TypeScript 加持:介面、類型檢查、編譯時錯誤發現

結語

JavaScript 通過「構造函數 + 原型」實現了基於原型的繼承,ES6 Class 為其提供了語法糖,ES2022 私有字段彌補了最後一塊拼圖。理解原型鏈查找、this 綁定、屬性遮蔽、繼承本質,是寫出高質量 JS 面向對象代碼的基石。

copyright © 萬盛學電腦網 all rights reserved