在實際專案中,我們通常用構造函數建立物件,再把常用方法掛到原型上,最後或直接實例化,或作為父類被繼承。繼承常見有兩種寫法,以下逐一探討。
// 父類
function Person(name){
this.name = name;
};
// 子類
function Student(sex){
Person.apply(this, arguments); // 繼承父類構造函數
this.sex = sex;
};
1. 繼承 Prototype
Student.prototype = Person.prototype;
// 執行完此句,Student.prototype.constructor 指向 Person,
// 因為 Person.prototype.constructor 指向 Person,而物件賦值其實是引用賦值
Student.prototype.constructor = Student; // 將 constructor 指回 Student
用父類原型覆蓋子類原型;由於是引用賦值,對 Student.prototype 的任何修改都會反映到 Person.prototype 上,也就是說子類會影響父類:
Student.prototype.add = function(){ alert("add"); };
Person.prototype.add(); // 彈出 add
2. 繼承實例
Student.prototype = new Person(); // 不傳參數時也可寫成 new Person
Student.prototype.constructor = Student;
用父類實例覆蓋子類原型;雖然比前一種耗用更多記憶體,卻也解決了子類影響父類的缺點——此時對 Student.prototype 的修改不會波及 Person.prototype。
3. 用空物件組合兩者優點
var F = function(){};
F.prototype = Person.prototype;
Student.prototype = new F();
Student.prototype.constructor = Student;
F 是個只有原型方法的空物件,實例化時記憶體佔用較少,同時也隔離了子類對父類的影響,可說是兼顧了前兩種做法的長處。