JS繼承的幾種方式

關(guān)于Js繼承的幾種方式,總結(jié)一下,以便查看。

第一種 prototype 引用型原型繼承

語言支持:js原生支持的繼承方式 構(gòu)造器的的prototype屬性作為類的原型 每個該類的對象都持有一個到原型的引用 當(dāng)對象中的屬性不存在時 可以訪問原型的屬性

代碼示例:

function parent(){

? ? ? this.x=10;

}

function child(){

}

child.prototype=new parent();

var childObj=new child();

alert(childObj.x);

第二種 復(fù)制型原型繼承

語言支持:js new運算符的性質(zhì) 當(dāng)構(gòu)造函數(shù)return值為非空對象時 new表達(dá)式返回return的對象

代碼示例:

function parent(){

? ? ? ? this.x=10;

}

function child(){

? ? ? var ret=new parent();

? ? ? ret.y=20;

? ? ? return ret;

}

var childObj=new child();

alert(childObj.x);

第三種 類繼承 屬性抄寫

語言支持:for in枚舉對象所有屬性

代碼示例:

function parent(){

? ? ? ? this.x=10;

}

function child(){

? ? ? var parentObj=new parent();

? ? ? for(var p in parentObj){

? ? ? ? ? ? ? this[p]=parentObj[p];

? ? ? }

}

var childObj=new child();

alert(childObj.x);

第四種 類繼承 對象冒充

語言支持:

1.動態(tài)添加和刪除方法

2.函數(shù)的call和apply

代碼示例:

function parent(){

? ? ? ? this.x=10;

}

function child(){

? ? ? ? this.parent=parent;

? ? ? ? this.parent();

? ? ? ? delete this.parent;

}

var childObj=new child();

alert(childObj.x);

function parent(){

? ? ? ? this.x=10;

}

function child(){

? ? ? ? ? parent.call(this);

}

var childObj=new child();

alert(childObj.x);

第五種 原型抄寫

語言支持:通過修改類的原型對象 可以為一類對象添加屬性和方法

代碼示例:

function parent(){}

parent.prototype.me=function(){

? ? ? ? alert("parent")

};

function child(){}

for(var p in parent.prototype){

? ? ? ? ? ? ? ? child.prototype[p]=parent.prototype[p];

}

var childObj=new child();

childObj.me();

第六種 元類

語言支持: js函數(shù)都是對象 且js函數(shù)可被構(gòu)造

代碼示例:

function parent(string){

? ? ? ? var child=new? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? Function("this.x=10;"+string);? ?

? ? ? ? return child;

}

var child=new parent("this.y=20;");

var childObj=new child();

alert(childObj.y);

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容