萬盛學電腦網

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

JavaScript 繼承機制深度解析:原型鏈、構造函數與 ES6 Class

JS 繼承的本質:原型鏈

JavaScript 沒有類(ES6 前),通過 原型鏈 實現繼承:每個對象有一個內部連結 [[Prototype]] 指向其原型對象,查找屬性時沿鏈向上尋找。

經典繼承模式對比

1. 原型鏈繼承(最基礎)

function Person() {
    this.name = "默認名";
    this.colors = ["red", "blue"]; // 引用類型會被共享!
}
Person.prototype.sayName = function() { console.log(this.name); };

function Student() {}
Student.prototype = new Person(); // 關鍵:原型指向父類實例

var s1 = new Student();
s1.colors.push("green"); // 修改引用類型
var s2 = new Student();
console.log(s2.colors); // ["red", "blue", "green"] — 污染!

❌ 缺點:引用類型屬性被所有實例共享;無法向父類構造函數傳參。

2. 借用構造函數(偽經典繼承)

function Person(name) {
    this.name = name;
    this.colors = ["red", "blue"];
}
function Student(name, grade) {
    Person.call(this, name); // 在子類構造函數中調用父類
    this.grade = grade;
}
var s1 = new Student("張三", 3);
var s2 = new Student("李四", 2);
s1.colors.push("green");
console.log(s2.colors); // ["red", "blue"] — 獨立 ✓

✅ 解決引用共享、可傳參;❌ 方法無法復用(每實例創建新函數)。

3. 組合繼承(最常用經典模式)

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

function Student(name, grade) {
    Person.call(this, name); // 第二次調用:實例屬性
    this.grade = grade;
}
Student.prototype = new Person(); // 第一次調用:原型方法
Student.prototype.constructor = Student; // 修正 constructor
Student.prototype.sayGrade = function() { console.log(this.grade); };

✅ 兼具原型方法復用與實例屬性隔離;❌ 調用兩次父類構造函數。

4. 寄生組合繼承(最佳實踐,ES6 前)

function inheritPrototype(Sub, Sup) {
    var prototype = Object.create(Sup.prototype); // 創建副本
    prototype.constructor = Sub;                  // 修正 constructor
    Sub.prototype = prototype;                    // 賦值
}

function Person(name) {
    this.name = name;
}
Person.prototype.sayName = function() { console.log(this.name); };

function Student(name, grade) {
    Person.call(this, name);
    this.grade = grade;
}
inheritPrototype(Student, Person); // 只調用一次父類構造函數
Student.prototype.sayGrade = function() { console.log(this.grade); };

✅ 只調用一次父類構造函數、原型鏈純淨、性能最優。

ES6 Class 繼承(語法糖,底層仍是原型)

class Person {
    constructor(name) { this.name = name; }
    sayName() { console.log(this.name); }
}

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

const s = new Student("王五", 4);
s.sayName();  // 王五
s.sayGrade(); // 4

原型鏈驗證實驗

function Person() { this.name = "A"; }
Person.prototype.age = 20;

var p = new Person();
console.log(p.age);      // 20 (來自原型)
p.age = 19;              // 實例新增同名屬性(遮蔽)
console.log(p.age);      // 19
delete p.age;            // 刪除實例屬性
console.log(p.age);      // 20 (恢復讀取原型) — 證明是鏈接非拷貝

總結建議

  • 現代項目:直接使用 class extends
  • 舊項目維護:採用寄生組合繼承
  • 理解原型鏈是調試繼承問題的關鍵
copyright © 萬盛學電腦網 all rights reserved