面向?qū)ο?/h2>

一、類的聲明

//構(gòu)造函數(shù)

function Parent() {

? ? this.firstName = 'Hou';

}

Parent.prototype.say(){

? ? console.log('hello');

}

//ES6

class Parent2(){

? ? consutractor () {

? ? ? ? this.name = 'Zhang';

? ? }

}

二、類的實(shí)例化

var parent= new Parent ();

三、類的繼承

1. 借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承

????原理:改變函數(shù)運(yùn)行時(shí)的上下文,即this的指向

function Child1() {

? ? Parent.call(this);

? ? this.lastName = 'Peng';

}

? ? 缺點(diǎn):父類原型對(duì)象上的方法無(wú)法被繼承

console.log(new Child1().say());? ? //出錯(cuò),找不到此方法

2. 借助原型鏈實(shí)現(xiàn)繼承

? ? 原理:改變子類的prototype(即其實(shí)例的__proto__)屬性指向其父類的實(shí)例

function Child2() {

? ? this.lastName = 'Peng';

}

Child2.prototype = new Parent();

? ??原型鏈原理:實(shí)例的__proto__屬性指向其構(gòu)造函數(shù)的prototype屬性

new Child2().__proto__ === Child2.prototype? ? //true

????缺點(diǎn):原型鏈中的原型對(duì)象是共用的,子類實(shí)例的原型對(duì)象是同一個(gè)引用,當(dāng)一個(gè)實(shí)例的屬性改變時(shí),其他實(shí)例也跟著改變

var c21 = new Child2();

var c22 = new Child2();

c21.__proto__ === c22.__proto__? ? //true

3. 組合方式實(shí)現(xiàn)繼承

? ? 原理:結(jié)合構(gòu)造函數(shù)和原型鏈方法的優(yōu)點(diǎn),彌補(bǔ)了此兩種方法的不足? ??

function Child3() {

? ? Parent.call(this);

? ? this.lastName = 'Peng';

}

Child3.prototype = new Parent();

? ? 缺點(diǎn):父類構(gòu)造函數(shù)執(zhí)行了兩次

4. 組合方式實(shí)現(xiàn)繼承的優(yōu)化1

? ? 原理:子類的原型對(duì)象引用父類的原型對(duì)象

function Child4() {

? ? Parent.call(this);

? ? this.lastName = 'Peng';

}

Child4.prototype= Parent.prototype;

? ? 缺點(diǎn):無(wú)法區(qū)分實(shí)例是子類還是父類的實(shí)例,實(shí)例的constructor屬性為父類構(gòu)造函數(shù)(方法2,3也有同樣的缺陷)

var c4 = new Child4();

console.log(c4 instanceof Child4);? ? //true

console.log(c4 instanceof Parent);? ? //true

console.log(c4.constructor);? ? //Parent;

5. 組合方式實(shí)現(xiàn)繼承的優(yōu)化2,完美寫(xiě)法

? ? 原理:利用Object.create()函數(shù)創(chuàng)建的對(duì)象

function Child5() {

? ? Parent.call(this);

? ? this.lastName = 'Peng';

}

Child5.prototype = Object.create(Parent.prototype);

Child5.prototype.constructor = Child5;

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

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

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