javascript 組合模式,對象冒充+原形鏈繼承

 

//使用對象冒充來繼承,只能繼承構造對象中的信息
//原形中的沒法繼承構造對象中的方法每次實例化都會分配空間
//形成空間浪費函數

 

function Box(name,age){
this.name=name;
this.age=age;
this.run=function(){
return this.name+this.age+"運行中..."
}
}
Box.prototype.family='加';
function Desk(name,age){
Box.call(this,name,age);

}
var desk=new Desk('lee',100);
alert(desk.run());

//原形鏈+構造函數的模式,叫作組合模式

function Box(name,age){
this.name=name;
this.age=age;

}
Box.prototype.run=function(){
return this.name+this.age+"運行中.."
}


function Desk(name,age){
Box.call(this,name,age); //對象冒充

}
Desk.prototype=new Box(); //原形鏈繼承
var desk=new Desk('lee',100);
alert(desk.run());this

相關文章
相關標籤/搜索