JavaScript 沒有 class 與 instance 的概念,也沒有父類子類,繼承完全靠原型鏈(prototype chain)實作:查找屬性時沿著原型鏈向上,直到找到為止。以下整理三種模擬類別的常見寫法。
function Animal() {
this.name = "animal";
}
Animal.prototype.makeSound = function() {
console.log("animal sound");
};
var animal1 = new Animal();
animal1.name; // 'animal'
animal1.makeSound(); // animal sound
也可以一次替換整個 prototype:
function Point(x, y) {
this.x = x;
this.y = y;
}
Point.prototype = {
method1: function() { console.log("method1"); },
method2: function() { console.log("method2"); }
};
var point1 = new Point(10, 20);
point1.method1(); // method1
point1.method2(); // method2
這裡有個細節:整體替換 prototype 後,最好補回 Point.prototype.constructor = Point,否則 constructor 會指向 Object。
var Animal = {
name: "animal",
makeSound: function() { console.log("animal sound"); }
};
var animal2 = Object.create(Animal);
animal2.name; // 'animal'
animal2.makeSound(); // animal sound
寫法比建構函式簡潔,但無法實作私有屬性與私有方法,實例之間也不能共享狀態,對類別的模擬不夠完整。
由荷蘭程式設計師 Gabor de Mooij 提出,不使用 prototype 與 this,改以 init 方法產生實例。
var Animal = {
init: function() {
var animal = {};
animal.name = "animal";
animal.makeSound = function() { console.log("animal sound"); };
return animal;
}
};
var animal3 = Animal.init();
animal3.name; // 'animal'
animal3.makeSound(); // animal sound
繼承只需在 init 中呼叫父類別的 init:
var Cat = {
init: function() {
var cat = Animal.init();
cat.name2 = "cat";
cat.makeSound = function() { console.log("cat sound"); }; // 類似方法重載
cat.sleep = function() { console.log("cat sleep"); };
return cat;
}
};
var cat = Cat.init();
cat.name; // 'animal'
cat.name2; // 'cat'
cat.makeSound(); // cat sound
cat.sleep(); // cat sleep
私有成員只要不打在回傳的物件上即可:
var Animal = {
init: function() {
var animal = {};
var sound = "private animal sound"; // 私有屬性
animal.makeSound = function() { console.log(sound); };
return animal;
}
};
var animal4 = Animal.init();
Animal.sound; // undefined
animal4.sound; // undefined,私有屬性只能透過自身方法讀取
animal4.makeSound(); // private animal sound
類別與實例之間若要共享資料,把狀態放在外層物件上即可:
var Animal = {
sound: "common animal sound", // 視為類屬性
init: function() {
var animal = {};
animal.commonSound = function() { console.log(Animal.sound); };
animal.changeSound = function() {
Animal.sound = "common animal sound changed";
};
return animal;
}
};
var animal5 = Animal.init();
var animal6 = Animal.init();
Animal.sound; // 'common animal sound'
animal5.sound; // undefined,實例無法直接存取類屬性
animal5.commonSound(); // common animal sound
animal6.commonSound(); // common animal sound
animal5.changeSound(); // 修改類屬性
animal6.commonSound(); // common animal sound changed,實例間共享同一份狀態
若一個實例改動了這個共有屬性,該類別與其他實例讀到的值也會隨之改變。
補充一句:ES2015 的 class 語法本質上仍是原型繼承,只是把上述寫法包成更清晰的形式;而 Object.create() 與極簡主義這兩種思路,在今天的元件設計中依然可見其影響。