這篇文章將為大家詳細(xì)講解有關(guān)javascript原型鏈中如何實(shí)現(xiàn)繼承,小編覺得挺實(shí)用的,因此分享給大家做個(gè)參考,希望大家閱讀完這篇文章后可以有所收獲。
成都創(chuàng)新互聯(lián)公司長期為1000多家客戶提供的網(wǎng)站建設(shè)服務(wù),團(tuán)隊(duì)從業(yè)經(jīng)驗(yàn)10年,關(guān)注不同地域、不同群體,并針對(duì)不同對(duì)象提供差異化的產(chǎn)品和服務(wù);打造開放共贏平臺(tái),與合作伙伴共同營造健康的互聯(lián)網(wǎng)生態(tài)環(huán)境。為招遠(yuǎn)企業(yè)提供專業(yè)的做網(wǎng)站、成都網(wǎng)站制作,招遠(yuǎn)網(wǎng)站改版等技術(shù)服務(wù)。擁有10余年豐富建站經(jīng)驗(yàn)和眾多成功案例,為您定制開發(fā)。具體如下:
繼承的幾種方式:
① 使用構(gòu)造函數(shù)實(shí)現(xiàn)繼承
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); //在子類函數(shù)體里面執(zhí)行父類的構(gòu)造函數(shù) this.type = 'child';//子類自己的屬性 }
Parent.call(this)
,this即實(shí)例,使用this執(zhí)行Parent方法,那么就用this.name = 'parent'
把屬性
掛載在了this(實(shí)例)上面,以此實(shí)現(xiàn)了繼承。
缺點(diǎn):以上只是讓Child得到了Parent上的屬性,Parent的原型鏈上的屬性并未被繼承。
② 使用原型鏈實(shí)現(xiàn)繼承
function Parent(){ this.name = 'parent'; } function Child(){ this.type = 'child'; } Child.prototype = new Parent();
解釋:Child.prototype === Chlid實(shí)例的__proto__ === Child實(shí)例的原型
所以當(dāng)我們引用new Child().name
時(shí),Child上沒有,然后尋找Child的原型child.__proto__
即Child.prototype
即new Parent()
,Parent的實(shí)例上就有name屬性,所以Child實(shí)例就在原型鏈上找到了name屬性,以此實(shí)現(xiàn)了繼承。
缺點(diǎn):可以看出,Child的所有實(shí)例,它們的原型都是同一個(gè),即Parent的實(shí)例:
var a = new Child(); var b = new Child(); a.__proto === b.__proto__; //true
所以,當(dāng)使用 a.name = 'a'重新給name賦值時(shí),b.name也變成了'a',反之亦然。
用instanceof和constructor都無法確認(rèn)實(shí)例到底是Child的還是Parent的。
③ 結(jié)合前兩種取長補(bǔ)短
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = new Parent();
缺點(diǎn):在Child()里面用Parent.call(this);
執(zhí)行了一次Parent(),然后又使用Child.prototype = new Parent()
執(zhí)行了一次Parent()。
改進(jìn)1:
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = Parent.prototype;
缺點(diǎn):用instanceof和constructor都無法確認(rèn)實(shí)例到底是Child的還是Parent的。
原因: Child.prototype = Parent.prototype
直接從Parent.prototype
里面拿到constructor,即Parent。
改進(jìn)2:
function Parent(){ this.name = 'parent'; } function Child(){ Parent.call(this); this.type = 'child'; } Child.prototype = Object.create(Parent.prototype); Child.prototype.constructor = Child;
畫圖說明吧:
var a = new Child();
所以這樣寫我們就構(gòu)造出了原型鏈。
關(guān)于“javascript原型鏈中如何實(shí)現(xiàn)繼承”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,使各位可以學(xué)到更多知識(shí),如果覺得文章不錯(cuò),請(qǐng)把它分享出去讓更多的人看到。
分享文章:javascript原型鏈中如何實(shí)現(xiàn)繼承-創(chuàng)新互聯(lián)
分享路徑:http://m.rwnh.cn/article28/cedpcp.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供企業(yè)網(wǎng)站制作、網(wǎng)站設(shè)計(jì)公司、網(wǎng)站建設(shè)、App開發(fā)、Google、動(dòng)態(tài)網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容