這裏有一份簡潔的前端知識體系等待你查收,看看吧,會有驚喜哦~若是以爲不錯,懇求star哈~前端
// 構造函數法
function Animal() {this.name = "name"};
------------------------------------------
// ES6類
class Animal {
constructor () {
this.name = "name";
}
}
------------------------------------------
// 類的實例化
new Animal
複製代碼
原型鏈git
/**
* 原理:改變父類構造函數運行時的this指向,從而實現了繼承
* 不足:只實現部分繼承,父類原型對象上的屬性/方法子類取不到。
*/
function Parent1 () {
this.name="parent1"
}
function Child1 () {
Parent.call(this);
this.type = "child1";
}
複製代碼
/**
* 原理:原理:new Child2 => new Child2.__proto__ === Child2.prototype => new Parent2() => new Parent2().__proto__ === Parent2.prototype,因此實現了Child2實例繼承自Parent2的原型對象。
* 不足:多個實例共用一個父類的實例對象,修改其中一個實例上的引用對象,會對其餘實例形成影響。
*/
function Parent2 () {
this.name = "parent2";
}
function Child2 () {
this.name = "child2";
}
Child2.prototype = new Parent2();
複製代碼
/**
* 優勢:彌補了原型鏈繼承的缺點,實例修改父類上的引用對象時,不會對其餘實際形成影響
* 不足:父級構造函數執行兩次,子類構造函數指向父類構造函數
*/
function Parent3 () {
this.name = "parent3";
}
function Child3 () {
Parent3.call(this);
}
Child3.prototype = new Parent3();
複製代碼
/**
* 組合方式優化
* 不足:子類構造函數仍舊指向父類構造函數
*/
function Parent4 () {
this.name = "parent4";
}
function Child4 () {
Parent4.call(this);
}
Child4.prototype = Parent4.prototype;
複製代碼
/**
* 優勢:Object.create()生成中間對象,隔離了子/父類原型對象,使之不會互相影響。
*/
function Parent5 () {
this.name = "parent5";
}
function Child5 () {
Parent5.call(this);
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
複製代碼