JavaScript 沒有類(ES6 前),通過 原型鏈 實現繼承:每個對象有一個內部連結 [[Prototype]] 指向其原型對象,查找屬性時沿鏈向上尋找。
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"] — 污染!
❌ 缺點:引用類型屬性被所有實例共享;無法向父類構造函數傳參。
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"] — 獨立 ✓
✅ 解決引用共享、可傳參;❌ 方法無法復用(每實例創建新函數)。
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); };
✅ 兼具原型方法復用與實例屬性隔離;❌ 調用兩次父類構造函數。
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); };
✅ 只調用一次父類構造函數、原型鏈純淨、性能最優。
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