繼承是面向?qū)ο笳Z言的必備特征,即一個類能夠重用另一個類的方法和屬性。在JavaScript中繼承方式的實(shí)現(xiàn)方式主要有以下五種:對象冒充、call()、apply()、原型鏈、混合方式。
下面分別介紹。
對象冒充
原理:構(gòu)造函數(shù)使用this關(guān)鍵字給所有屬性和方法賦值。因?yàn)闃?gòu)造函數(shù)只是一個函數(shù),所以可以使ClassA的構(gòu)造函數(shù)成為ClassB的方法,然后調(diào)用它。ClassB就會收到ClassA的構(gòu)造函數(shù)中定義的屬性和方法。
示例:
代碼如下:
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);
}
}
調(diào)用:
代碼如下:
var objb=new ClassB("blue","Test");
objb.sayColor();//
blueobjb.sayName(); // Test
注意:這里要刪除對ClassA的引用,否則在后面定義新的方法和屬性會覆蓋超類的相關(guān)屬性和方法。用這種方式可以實(shí)現(xiàn)多重繼承。
call()方法
由于對象冒充方法的流行,在ECMAScript的第三版對Function對象加入了兩個新方法 call()和apply()方法來實(shí)現(xiàn)相似功能。
call()方法的第一個參數(shù)用作this的對象,其他參數(shù)都直接傳遞給函數(shù)自身。示例:
代碼如下:
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.");
使用此方法來實(shí)現(xiàn)繼承,只需要將前三行的賦值、調(diào)用、刪除代碼替換即可:
代碼如下:
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()方法類似,不同的是第二個參數(shù),在apply()方法中傳遞的是一個數(shù)組。
代碼如下:
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."));
使用此方法來實(shí)現(xiàn)繼承,只需要將前三行的賦值、調(diào)用、刪除代碼替換即可:
代碼如下:
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);
}
}
跟call()有一點(diǎn)不同的是,如果超類中的參數(shù)順序與子類中的參數(shù)順序完全一致,第二個參數(shù)可以用arguments。
原型鏈
繼承這種形式在ECMAScript中原本是用于原型鏈的。Prototype對象的任何屬性和方法都被傳遞給那個類的所有實(shí)例。原型鏈利用這種功能實(shí)現(xiàn)繼承機(jī)制。
用原型鏈實(shí)現(xiàn)繼承示例:
代碼如下:
function ClassA(){
}
ClassA.prototype.color="red";
ClassA.prototype.sayColor=function(){
alert(this.color);
};
function ClassB(){
}
ClassB.prototype=new ClassA();
注意:調(diào)用ClassA的構(gòu)造函數(shù)時,沒有給它傳遞參數(shù)。這在原型鏈中是標(biāo)準(zhǔn)的做法,要確保構(gòu)造函數(shù)沒有任何參數(shù)。
混合方式
這種方式混合了對象冒充和原型鏈方式。示例:
代碼如下:
function ClassA(sColor){
this.color=sColor;
}
ClassA.prototype.sayColor=function(){
alert(this.color);
}
function ClassB(sColor,sName){
ClassA.call(this,sColor);
this.name=sName;
}
ClassB.prototype=new ClassA();
ClassB.prototype.sayName=function(){
alert(this.name);
}
調(diào)用示例:
代碼如下:
var objb=new ClassB("red","test");
objb.sayColor();// output red
objb.sayName();// output test
作者:Artwl
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com