JavaScript 是基於原型(prototype)的語言,在 ES6 之前並沒有類別的概念,我們能碰到的都是物件。也正因如此,「類型的物件」和「物件本身」這兩個概念很容易搞混。為了方便理解,以下改用與 Java 相近的說法來描述。
先看一段最基礎的宣告,順便釐清哪些成員能被繼承:
function Person(name, id){
this.name = name; // 實例屬性,可被繼承
var id = id; // 私有變數,無法被繼承
function speak(){ // 私有函式,無法被繼承
alert("person1");
}
}
Person.age = 18; // 靜態屬性,無法被繼承
Person.prototype.sex = "男"; // 公開的靜態成員,可被繼承
Person.prototype.say = function(){ // 公開方法,可被繼承
alert("person2");
}
// 建立子類
function Student(){ }
// 繼承 Person
Student.prototype = new Person("iwen", 1);
// 修正因繼承而改變的 constructor
Student.prototype.constructor = Student;
var s = new Student();
alert(s.name); //iwen
alert(s instanceof Person); //true
s.say(); //person2
先把父類方法存起來,覆寫之後再透過 call 回頭呼叫,就等同於其他語言的 super。
// 保存父類方法的引用
var superPerson = Student.prototype.say;
// 覆寫父類方法
Student.prototype.say = function(){
superPerson.call(this); // 呼叫父類的 say
alert("Student");
};
var s = new Student();
alert(s instanceof Person); //true
s.say(); //person2 接著 student
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
這裡用一個空函式 F 充當中介,避免為了繼承而多執行一次父類建構函式。至於 uber(德語,意為「向上、上一層」),它讓子物件多開一條通道可以直接存取父類原型上的方法,屬於完備性考量下的備用設計。
第二種寫法比較接近「拷貝」的直覺:在父類中建一個 _this 物件,把希望被繼承的成員掛上去並回傳;子類只要取得這個 _this,就完成了繼承。
// 建立父類
function Person(name, id){
// 用一個物件承載父類所有公開內容,只有掛在 _this 上的才會被傳下去
var _this = {};
_this.name = name;
this.id = id; // 掛在 this 上的不會傳遞
_this.say = function(){
alert("Person");
};
return _this;
}
// 子類
function Student(){
// 取得 Person 的 _this 物件,藉此模擬繼承
var _this = Person("iwen", 1);
// 保存父類的 _this 方法引用
var superPerson = _this.say;
// 覆寫父類方法
_this.say = function(){
superPerson.call(_this); // 執行父類的 say
alert("Student");
};
return _this;
}
var s = new Student();
s.say();
兩種方式各有適用場景:原型鏈繼承更貼近 JavaScript 的語言本質,也更容易被框架與工具辨識;_this 承載式則可讀性更高,適合小型模組。希望這些示例對你理解 JavaScript 物件導向有幫助。