Prototype 是 JavaScript 面向對象編程的核心,但常被誤解。本文通過實例系統梳理原型鏈、方法類型區分、call/apply 借用機制及繼承模式。
function People(name) {
this.name = name;
// 實例方法:每個實例擁有副本
this.Introduce = function() { alert('My name is ' + this.name); };
}
// 類方法(靜態方法):屬於構造函數本身
People.Run = function() { alert('I can run'); };
// 原型方法:所有實例共享
People.prototype.IntroduceChinese = function() {
alert('我的名字是' + this.name);
};
function Base() { this.show = function() { alert('Base'); }; }
function Extend() {}
Extend.prototype = new Base(); // Extend 原型指向 Base 實例
var instance = new Extend();
instance.show(); // 彈出 "Base" - 實際是向上查找原型鏈
關鍵點: JS 沒有類式繼承,prototype 是對象引用鏈。查找屬性時:實例自身 → 構造函數 prototype → 更上層 prototype → null。
function Base() { this.show = function() { alert('Base'); }; }
function Extend() {
this.show = function() { alert('Extend'); }; // 實例方法覆蓋原型方法
}
Extend.prototype = new Base();
var inst = new Extend();
inst.show(); // "Extend" - 優先查找實例自身
// 強制調用原型方法:使用 call 改變 this 指向
var baseInst = new Base();
baseInst.show.call(inst); // "Base" - 以 inst 作為 this 調用 baseInst.show
function Base() {
this.objMethod = function() { alert('Base obj'); };
this.baseOnly = function() { alert('Base only'); };
}
Base.staticMethod = function() { alert('Base static'); };
function Extend() {
this.objMethod = function() { alert('Extend obj'); };
}
Extend.staticMethod = function() { alert('Extend static'); };
Extend.prototype = new Base();
var e = new Extend();
e.objMethod(); // Extend obj (實例方法)
e.baseOnly(); // Base only (原型鏈查找)
Base.staticMethod.call(e); // Base static (類方法借用)
Extend.staticMethod(); // Extend static
prototype,節省內存。Object.create() 建立純原型鏈繼承,避免構造函數副作用。class 語法糖底層仍是原型機制,理解原型有助於深度掌握。