前端面試6:面向對象

這裏有一份簡潔的前端知識體系等待你查收,看看吧,會有驚喜哦~若是以爲不錯,懇求star哈~前端


課程思惟導圖

面向對象.png

Q:類的聲明有哪些方式,如何實例化?

// 構造函數法
function Animal() {this.name = "name"};
------------------------------------------
// ES6類
class Animal {
    constructor () {
        this.name = "name";
    }
}
------------------------------------------
// 類的實例化
new Animal
複製代碼

Q:繼承的本質是?

原型鏈git

Q:如何實現繼承?

1、藉助構造函數實現繼承

/**
 * 原理:改變父類構造函數運行時的this指向,從而實現了繼承
 * 不足:只實現部分繼承,父類原型對象上的屬性/方法子類取不到。
 */
function Parent1 () {
    this.name="parent1"
}
function Child1 () {
    Parent.call(this);
    this.type = "child1";
}
複製代碼

2、藉助原型鏈實現繼承

/**
 * 原理:原理: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();
複製代碼

3、組合方式實現繼承

/**
 * 優勢:彌補了原型鏈繼承的缺點,實例修改父類上的引用對象時,不會對其餘實際形成影響
 * 不足:父級構造函數執行兩次,子類構造函數指向父類構造函數
 */
function Parent3 () {
    this.name = "parent3";
}
function Child3 () {
    Parent3.call(this);
}
Child3.prototype = new Parent3();
複製代碼

4、組合方式優化

/**
 * 組合方式優化
 * 不足:子類構造函數仍舊指向父類構造函數
 */
function Parent4 () {
    this.name = "parent4";
}
function Child4 () {
    Parent4.call(this);
}
Child4.prototype = Parent4.prototype;
複製代碼

5、組合繼承方式的完美方案

/**
 * 優勢:Object.create()生成中間對象,隔離了子/父類原型對象,使之不會互相影響。
 */
function Parent5 () {
    this.name = "parent5";
}
function Child5 () {
    Parent5.call(this);
}
Child5.prototype = Object.create(Parent5.prototype);
Child5.prototype.constructor = Child5;
複製代碼
相關文章
相關標籤/搜索