javascript面向物件程式設計--繼承--類繼承2(封裝類繼承模式)
阿新 • • 發佈:2018-12-11
function extend(Sub,Sup){
var F=function(){};
F.prototype=Sup.prototype;
Sub.prototype=new F();
Sub.prototype.constructor=Sub;
Sub.sup=Sup.prototype;// 在子類中定義一個本地屬性儲存超類原型,這樣可以避免子類和超累耦合
if(Sup.prototype.constructor==Object.prototype.constructor){//檢測超類的原型構造器是否為自身
Sup.prototype.constructor=Sup //類繼承 封裝函式
}
}
function A(x){
this.x=x;
this.get=function(){return this.x;}
}
A.prototype.add=funciton(){return this.x+this.x}
A.prototype.mul=funciton(){return this.x*this.x}
function B(x){
A.call(this,x) //
}
extend(B,A);
B.prototype.add=function(){ return this.x+''+this.x}//55,覆蓋了超類A的原型方法
B.prototype.add=function(){ return B.sup.add.call(this)}//在B類呼叫超類A的原型方法,避免程式碼耦合現象發生
var f=new B(5);
alert(f.get()) //5
alert(f.add())//10
alert(f.mul())//25