標籤:func 耦合 設定 style tor 好處 使用 == 儲存
實現原理:定義一個封裝函數extend;該函數有2個參數,Child代表子類,Parent代表父類;在函數內,先定義一個空函數F, 用來實現功能中轉,設定F的原型為父類的原型,然後把空函數的執行個體傳遞給子類的原型,使用空函數的好處:避免直接執行個體化父類可能會帶來系統效能問題,比如父類的執行個體很大的話,執行個體化會佔用很多記憶體;
function extend(Child,Parent) {
//Child表示子類,Parent表示父類
// 首先定義一個空函數
var F = function(){};
// 設定空函數的原型為父類的原型
F.prototype = Parent.prototype;
// 執行個體化空函數,並把父類原型引用傳遞給子類
Child.prototype = new F();
// 重設子類原型的構造器為子類自身
Child.prototype.constructor = Child;
// 在子類中儲存父類的原型,避免子類與父類別結合程度
Child.parent = Parent.prototype;
if(Parent.prototype.constructor !== Parent) {
// 檢測父類原型的構造器是否為原型自身
Parent.prototype.constructor = Parent;
}
}
測試代碼如下:
// 下面我們定義2個類A和類B,我們目的是實現B繼承於A
function A(x) {
this.x = x;
this.getX = function(){
return this.x;
}
}
A.prototype.add = function(){
return this.x + this.x;
}
A.prototype.mul = function(){
return this.x * this.x;
}
// 建構函式B
function B(x){
A.call(this,x); // 繼承建構函式A中的所有屬性及方法
}
extend(B,A); // B繼承於A
var b = new B(10);
console.log(b.getX()); // 10
console.log(b.add()); // 20
console.log(b.mul()); //100
js 封裝類實現原型繼承