萬盛學電腦網

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

JavaScript 面向對象編程核心機制深度解析:類型、引用、原型、封裝繼承多態

一、數據類型體系

包裝類typeof 結果典型值分類
Number"number"123.45基本型別
Boolean"boolean"true/false
String"string""hello"
Object"object"{}, []複合型別
Function"function"function(){}
無"undefined"undefined特殊型別
無"object" (Bug)null

二、引用型別 vs 值型別

  • 引用型別:Object、Function、Array、Date、RegExp… 變量存儲堆內存地址,賦值/傳參複製地址
  • 值型別:number、boolean、string、null、undefined。變量直接存儲值,賦值/傳參複製值
let a = {x:1}, b = a; b.x = 2; console.log(a.x); // 2 (共享同一對象)
let p = 10, q = p; q = 20; console.log(p); // 10 (獨立副本)

三、new Function 構造過程與 prototype 原型鏈

function ClassName() { this.id = 0; }
const v = new ClassName();

內部 5 步驟:

  1. 查找 ClassName.prototype,淺拷貝其屬性到新對象
  2. this 綁定新對象
  3. 設置 this.constructor = ClassName
  4. 執行構造函數體代碼
  5. 返回 this 賦予左值

註:ClassName.prototype.constructor 默認也指向 ClassName,步驟 3 實例屬性覆蓋原型屬性。

四、實現面向對象三大特征

1. 封裝:利用閉包模擬私有成員

function ClassName(a) {
    // 私有:僅構造函數作用域可訪問
    let uid = a; 

    // 特權方法:訪問私有變量的公共接口
    this.getUid = () => uid;        // 只讀
    this.setUid = (val) => { uid = val; }; // 可寫

    // 公共屬性
    this.id = uid; 
}

// 原型方法:公共行為
ClassName.prototype.func = function() { ... };

// 靜態屬性/方法:屬於構造函數本身
ClassName.staticProp = "static";
ClassName.staticMethod = function() { ... };

2. 繼承:原型鏈 + 建構函數盜用 (組合繼承)

function Parent(name) {
    this.name = name;
    this.colors = ["red", "blue"];
}
Parent.prototype.sayName = function() { console.log(this.name); };

function Child(name, age) {
    Parent.call(this, name); // 盜用構造函數:繼承實例屬性 (含引用類型獨立副本)
    this.age = age;
}

// 原型鏈繼承方法
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;

// 子類擴展
Child.prototype.sayAge = function() { console.log(this.age); };

const child = new Child("Tom", 10);
child.sayName(); // "Tom"
child.colors.push("green"); // 不影響 Parent.prototype.colors
console.log(child.colors); // ["red", "blue", "green"]

3. 多態:動態綁定與方法重寫

class Animal {
    speak() { console.log("Animal sound"); }
}
class Dog extends Animal {
    speak() { console.log("Woof"); } // 重寫
}
class Cat extends Animal {
    speak() { console.log("Meow"); }
}

function makeSpeak(animal) {
    animal.speak(); // 運行時根據實際類型調用
}

makeSpeak(new Dog()); // "Woof"
makeSpeak(new Cat()); // "Meow"

五、ES6 Class 語法糖 (標準化、更安全)

class Person {
    #privateField = "secret"; // 真私有 (Stage 3)

    constructor(name, age) {
        this.name = name;
        this.age = age;
    }

    // 實例方法 (自動定義在 prototype)
    greet() {
        console.log(`Hi, I'm ${this.name}, ${this.age}`);
    }

    // 存取器
    get info() { return `${this.name} (${this.age})`; }
    set info(val) { [this.name, this.age] = val.split(" "); }

    // 靜態方法
    static species() { return "Homo sapiens"; }
}

class Employee extends Person {
    constructor(name, age, dept) {
        super(name, age); // 必須先調用 super()
        this.dept = dept;
    }
    // 重寫
    greet() {
        super.greet(); // 呼叫父類方法
        console.log(`Dept: ${this.dept}`);
    }
}

六、最佳實踐與避坑

  1. 優先 Class:語法清晰、自動嚴格模式、防止忘記 new
  2. 方法放 prototype/類體:別在構造函數內定義函數 (每實例重複創建)
  3. 慎用 this:回調/事件處理器用箭頭函數 () => this.method() 或 .bind(this)
  4. 組合 > 繼承:const user = Object.assign({}, authMixin, logMixin)
  5. 不可變數據:Object.freeze()、Readonly<T> (TS)、Immer 庫
  6. 避免修改內建原型:Array.prototype.xxx = ... 污染全局,極易衝突
copyright © 萬盛學電腦網 all rights reserved