JavaScript 沒有類(Class),只有物件。每個函數都有 prototype 屬性指向一個「原型物件」,所有實例共享此原型上的屬性與方法。本文從成員分類、原型定義、原型鏈機制、繼承本質四個維度,建立完整心智模型。
function Box() {
var color = 'blue'; // 私有變數
var secret = function() {}; // 私有函式
// 外部無法存取 color、secret
}
透過閉包實現封裝,外部不可直接存取。
function Obj() {}
Obj.num = 72; // 靜態屬性
Obj.staticMethod = function() {}; // 靜態方法
console.log(Obj.num); // 72
var o = new Obj();
console.log(o.num); // undefined(實例不共享靜態成員)
掛在建構函數本身,屬於「類別層級」。
function Box() {
this.arr = []; // 實例屬性
this.method = function() {}; // 實例方法(每個實例各有一份副本)
}
每 new 一次就建立一份副本,方法重複佔用記憶體。
function Box() {
this.arr = []; // 實例屬性(引用型別需放在建構函數,避免共享)
}
Box.prototype.method = function() {}; // 所有實例共享同一個函式
Person 有 prototype 指向原型物件。person1 內部有 [[Prototype]](__proto__)指向 Person.prototype。constructor 指回建構函數。Object.prototype 是鏈路終點,其 __proto__ === null。
hasOwnProperty 為 true)。__proto__ 往上找原型鏈,直到 null。undefined。delete obj.prop 僅刪除實例屬性,原型屬性不受影響。
A.prototype = new B();
// 理解:A 的原型指向 B 的一個實例
// 並非複製 B 的成員,而是建立原型鏈:A 實例 → B 實例 → B.prototype → Object.prototype
重點:JS 繼承是委託機制,而非複製。修改 B.prototype 會影響所有繼承鏈上的實例。
function Parent(name) {
this.name = name;
this.arr = ['a', 'b'];
}
Parent.prototype.say = function() { console.log(this.name); };
function Child(name, age) {
Parent.call(this, name); // 繼承實例屬性(解決引用共享)
this.age = age;
}
Child.prototype = new Parent(); // 繼承原型方法
Child.prototype.constructor = Child; // 修正 constructor
var c1 = new Child('Tom', 18);
c1.arr.push('c');
var c2 = new Child('Jerry', 20);
console.log(c2.arr); // ['a', 'b'] 不受 c1 影響
function inheritPrototype(Sub, Sup) {
var prototype = Object.create(Sup.prototype); // 建立中介物件
prototype.constructor = Sub; // 修正 constructor
Sub.prototype = prototype; // 指定子類原型
}
優點:只呼叫一次父類建構函數,避免屬性重複初始化。
// 為所有陣列新增 first() 方法
Array.prototype.first = function() { return this[0]; };
[1,2,3].first(); // 1
// 修補舊瀏覽器缺少的方法
if (!Array.prototype.includes) {
Array.prototype.includes = function(item) {
return this.indexOf(item) > -1;
};
}
警告:修改內建原型汙染全域環境,庫開發請改用獨立工具函式或 Symbol 避免衝突。
原型鏈是 JavaScript 物件導向的骨架。理解「成員分類 → 原型鏈查找 → 委託繼承」三部曲,即可駕馭從元件封裝到框架設計的各種進階場景。