課程思維導(dǎo)圖

面向?qū)ο?png
Q:類(lèi)的聲明有哪些方式,如何實(shí)例化?
```javascript
// 構(gòu)造函數(shù)法
function Animal() {this.name = "name"};
------------------------------------------
// ES6類(lèi)
class Animal {
constructor () {
this.name = "name";
}
}
------------------------------------------
// 類(lèi)的實(shí)例化
new Animal
```
Q:繼承的本質(zhì)是?
原型鏈
Q:如何實(shí)現(xiàn)繼承?
一、借助構(gòu)造函數(shù)實(shí)現(xiàn)繼承
```javascript
/**
* 原理:改變父類(lèi)構(gòu)造函數(shù)運(yùn)行時(shí)的this指向,從而實(shí)現(xiàn)了繼承
* 不足:只實(shí)現(xiàn)部分繼承,父類(lèi)原型對(duì)象上的屬性/方法子類(lèi)取不到。
*/
function Parent1 () {
this.name="parent1"
}
function Child1 () {
Parent.call(this);
this.type = "child1";
}
```
二、借助原型鏈實(shí)現(xiàn)繼承
```javascript
/**
* 原理:原理:new Child2 => new Child2.__proto__ === Child2.prototype => new Parent2() => new Parent2().__proto__ === Parent2.prototype,所以實(shí)現(xiàn)了Child2實(shí)例繼承自Parent2的原型對(duì)象。
* 不足:多個(gè)實(shí)例共用一個(gè)父類(lèi)的實(shí)例對(duì)象,修改其中一個(gè)實(shí)例上的引用對(duì)象,會(huì)對(duì)其他實(shí)例造成影響。
*/
function Parent2 () {
this.name = "parent2";
}
function Child2 () {
this.name = "child2";
}
Child2.prototype = new Parent2();
```
三、組合方式實(shí)現(xiàn)繼承
```javascript
/**
* 優(yōu)點(diǎn):彌補(bǔ)了原型鏈繼承的缺點(diǎn),實(shí)例修改父類(lèi)上的引用對(duì)象時(shí),不會(huì)對(duì)其他實(shí)際造成影響
* 不足:父級(jí)構(gòu)造函數(shù)執(zhí)行兩次,子類(lèi)構(gòu)造函數(shù)指向父類(lèi)構(gòu)造函數(shù)
*/
function Parent3 () {
this.name = "parent3";
}
function Child3 () {
Parent3.call(this);
}
Child3.prototype = new Parent3();
```
四、組合方式優(yōu)化
```javascript
/**
* 組合方式優(yōu)化
* 不足:子類(lèi)構(gòu)造函數(shù)仍舊指向父類(lèi)構(gòu)造函數(shù)
*/
function Parent4 () {
this.name = "parent4";
}
function Child4 () {
Parent4.call(this);
}
Child4.prototype = Parent4.prototype;
```
五、組合繼承方式的完美方案
```javascript
/**
* 優(yōu)點(diǎn):Object.create()生成中間對(duì)象,隔離了子/父類(lèi)原型對(duì)象,使之不會(huì)互相影響。
*/
function Parent5 () {
this.name = "parent5";
}
function Child5 () {
Parent5.call(this);
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
```