JavaScript高級程序設計 閱讀筆記(十四) js繼承機制的實現
2024-05-06 14:21:23
供稿:網友
繼承
繼承是面向對象語言的必備特征,即一個類能夠重用另一個類的方法和屬性。在JavaScript中繼承方式的實現方式主要有以下五種:對象冒充、call()、apply()、原型鏈、混合方式。
下面分別介紹。
對象冒充
原理:構造函數使用this關鍵字給所有屬性和方法賦值。因為構造函數只是一個函數,所以可以使ClassA的構造函數成為ClassB的方法,然后調用它。ClassB就會收到ClassA的構造函數中定義的屬性和方法。
示例:
代碼如下:
function ClassA(sColor){
this.color=sColor;
this.sayColor=function(){
alert(this.color);
}
}
function ClassB(sColor,sName){
this.newMethod=ClassA;
this.newMethod(sColor);
delete this.newMethod;
this.name=sName;
this.sayName=function(){
alert(this.name);
}
}
調用:
代碼如下:
var objb=new ClassB("blue","Test");
objb.sayColor();//
blueobjb.sayName(); // Test
注意:這里要刪除對ClassA的引用,否則在后面定義新的方法和屬性會覆蓋超類的相關屬性和方法。用這種方式可以實現多重繼承。
call()方法
由于對象冒充方法的流行,在ECMAScript的第三版對Function對象加入了兩個新方法 call()和apply()方法來實現相似功能。
call()方法的第一個參數用作this的對象,其他參數都直接傳遞給函數自身。示例:
代碼如下:
function sayColor(sPrefix,sSuffix){
alert(sPrefix+this.color+sSuffix);
}
var obj=new Object();
obj.color="red";
//output The color is red, a very nice color indeed.
sayColor.call(obj,"The color is ",", a very nice color indeed.");
使用此方法來實現繼承,只需要將前三行的賦值、調用、刪除代碼替換即可:
代碼如下:
function ClassB(sColor,sName){
//this.newMethod=ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.call(this,sColor);
this.name=sName;
this.sayName=function(){
alert(this.name);
}
}
apply()方法
apply()方法跟call()方法類似,不同的是第二個參數,在apply()方法中傳遞的是一個數組。
代碼如下:
function sayColor(sPrefix,sSuffix){
alert(sPrefix+this.color+sSuffix);
}
var obj=new Object();
obj.color="red";
//output The color is red, a very nice color indeed.
sayColor.apply(obj,new Array("The color is ",", a very nice color indeed."));
使用此方法來實現繼承,只需要將前三行的賦值、調用、刪除代碼替換即可:
代碼如下:
function ClassB(sColor,sName){
//this.newMethod=ClassA;
//this.newMethod(sColor);
//delete this.newMethod;
ClassA.apply(this,new Array(sColor));
this.name=sName;
this.sayName=function(){
alert(this.name);
}