一、 簡(jiǎn)單原型繼承
function Parent() {
this.a = 1;
this.b = [1];
}
Parent.prototype.hello = function() {}
function Child(name) {
this.name = name;
}
Child.prototype = new Parent(); // 核心
Child.prototype.constructor = Child; // 修正Child的構(gòu)造函數(shù)
let child1 = new Child("child1");
let child2 = new Child("child2");
核心:使用父類的實(shí)例來作為子類的原型對(duì)象
缺點(diǎn):1.父類的引用屬性會(huì)在子類實(shí)例中共享 2.創(chuàng)建子類實(shí)例時(shí)無法給父類構(gòu)造函數(shù)傳參
二、 借用構(gòu)造函數(shù)
function Parent(num) {
this.a = num;
this.b = [1];
this.hello2 = function() {} // 此函數(shù)會(huì)被復(fù)制到子類
}
Parent.prototype.hello = function() {} // 此函數(shù)不會(huì)被復(fù)制到子類
function Child(name, num) {
Parent.call(this, num); // 核心
this.name = name;
}
let child1 = new Child("child1", 1);
let child2 = new Child("child2", 2);
核心:借用父類的構(gòu)造函數(shù),將父類的屬性復(fù)制給子類實(shí)例,沒有用到原型
優(yōu)點(diǎn):解決了簡(jiǎn)單原型繼承的兩個(gè)問題
缺點(diǎn):由于沒有用到原型,父類復(fù)制來的函數(shù)無法實(shí)現(xiàn)復(fù)用
三、 組合繼承
function Parent(num) {
this.a = num;
this.b = [1];
}
Parent.prototype.hello = function() {}
function Child(name, num) {
Parent.call(this, num); // 核心
this.name = name;
}
Child.prototype = new Parent(); // 核心,此處實(shí)例化了一個(gè)多余的父類對(duì)象
Child.prototype.constructor = Child; // 修正Child的構(gòu)造函數(shù)
let child1 = new Child("child1", 1);
let child2 = new Child("child2", 2);
核心:將上述兩種方式組合起來使用,將需要復(fù)用的函數(shù)都放在原型上,將需要復(fù)制的屬性通過借用構(gòu)造函數(shù)復(fù)制給子類實(shí)例
優(yōu)點(diǎn):解決了所有問題
缺點(diǎn):實(shí)例化了一個(gè)“多余”的父類對(duì)象
四、 寄生組合繼承
function Parent(num) {
this.a = num;
this.b = [1];
}
Parent.prototype.hello = function() {}
function Child(name, num) {
Parent.call(this, num); // 核心
this.name = name;
}
function extend(child, parent) {
let F = function() {};
F.prototype = parent.prototype;
child.prototype = new F(); // 核心,用一個(gè)空函數(shù)來避免實(shí)例化屬性的浪費(fèi)
child.prototype.constructor = child; // 修正構(gòu)造函數(shù)
}
extend(Child, Parent); // 核心
let child1 = new Child("child1", 1);
let child2 = new Child("child2", 2);
核心:與組合繼承基本一樣,只是針對(duì)多余的實(shí)例化進(jìn)行了優(yōu)化
優(yōu)點(diǎn):解決了所有問題
缺點(diǎn):比較麻煩……