萬盛學電腦網

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

JavaScript 類別模擬完整指南:建構函式、原型、私有/公有/靜態成員、繼承與 this 綁定陷阱

ES5 建構函式模擬類別

1. 基本建構與實例屬性

function Shape(x, y) {
    // 公有屬性
    this.x = x;
    this.y = y;
    // 私有變數(閉包)
    let _id = Shape._nextId++;
    // 特權方法存取私有變數
    this.getId = () => _id;
}
Shape._nextId = 0;

const s = new Shape(1, 2);
console.log(s.x, s.y, s.getId()); // 1 2 0

2. 原型方法(共享)

Shape.prototype = {
    move(dx, dy) { this.x += dx; this.y += dy; },
    toString() { return `Shape(${this.x},${this.y})`; }
};

3. 靜態屬性/方法(掛在建構函式上)

Shape.count = 0;
Shape.createOrigin = () => new Shape(0, 0);

4. 繼承:原型鏈 + 建構函式借用

function Circle(x, y, r) {
    Shape.call(this, x, y); // 繼承實例屬性
    this.r = r;
}
// 原型繼承
Circle.prototype = Object.create(Shape.prototype);
Circle.prototype.constructor = Circle;
// 擴充/覆寫
Circle.prototype.area = function() { return Math.PI * this.r ** 2; };
Circle.prototype.toString = function() { return `Circle(${this.x},${this.y}, r=${this.r})`; };

ES6 Class 語法糖(標準化、更清晰)

class Shape {
    static count = 0;
    #id; // 私有欄位 (Stage 3, 現代瀏覽器/Node 12+ 支援)

    constructor(x, y) {
        this.x = x; this.y = y;
        this.#id = Shape.count++;
    }
    getId() { return this.#id; }
    move(dx, dy) { this.x += dx; this.y += dy; }
    toString() { return `Shape(${this.x},${this.y})`; }
    static createOrigin() { return new Shape(0, 0); }
}

class Circle extends Shape {
    constructor(x, y, r) {
        super(x, y);
        this.r = r;
    }
    area() { return Math.PI * this.r ** 2; }
    toString() { return `Circle(${this.x},${this.y}, r=${this.r})`; }
}

this 綁定陷阱與解決方案

場景問題解決
事件處理器 el.onclick = obj.handlerthis 指向 el箭頭函數屬性 handler = () => {}、.bind(this)、addEventListener(e => this.handler(e))
回呼傳遞 setTimeout(obj.method, 100)this 丟失setTimeout(() => obj.method(), 100) 或 obj.method.bind(obj)
解構賦值 const {method} = objmethod() 時 this 為 undefined保留物件引用 obj.method() 或 const bound = obj.method.bind(obj)

經典 _this = this 模式(ES5 相容)

function Person(name) {
    const _this = this; // 捕獲外層 this
    this.name = name;
    this.sayLater = function() {
        setTimeout(function() {
            console.log(_this.name); // 正確
        }, 1000);
    };
}

總結

ES6 class、私有欄位 #field、extends/super 已成標準,**新專案首選 Class**。維護 ES5 代碼時,掌握「建構函式 + 原型 + 閉包私有 + 寄生組合繼承」模式,並謹記 this 只在呼叫時決定,善用箭頭函數與 bind 固定上下文。

copyright © 萬盛學電腦網 all rights reserved