前端面試知識點--面向對象

類與實例

類的聲明

var Animal = function () {
    this.name = 'Animal';
};

/**
 * es6中class的聲明
 */
class Animal2 {
    constructor () {
        this.name = 'Animal2';
    }
}

實例化

console.log(new Animal(), new Animal2());

類的繼承

藉助構造函數實現繼承
缺點:無法繼承父類原型對象上的方法,實現了部分繼承;但如果父類的屬性在構造函數中可以實現繼承。

function Parent1 () {
    this.name = 'parent1';
}
Parent1.prototype.say = function () {
};
function Child1 () {
    Parent1.call(this);
    this.type = 'child1';
}
console.log(new Child1(), new Child1().say());

藉助原型鏈實現繼承
缺點:由於原型鏈中的原型對象是共享的,所以在一個實例更改其屬性值時,另外一個實例所對應的屬性值也會更改。

function Parent2 () {
    this.name = 'parent2';
    this.play = [1, 2, 3];
}
function Child2 () {
    this.type = 'child2';
}
Child2.prototype = new Parent2();

var s1 = new Child2();
var s2 = new Child2();
console.log(s1.play, s2.play);
s1.play.push(4);

組合方式
缺點:父級的構造函數執行了兩次

function Parent3 () {
    this.name = 'parent3';
    this.play = [1, 2, 3];
}
function Child3 () {
    Parent3.call(this);
    this.type = 'child3';
}
Child3.prototype = new Parent3();
var s3 = new Child3();
var s4 = new Child3();
s3.play.push(4);
console.log(s3.play, s4.play);

組合繼承的優化1

function Parent4 () {
    this.name = 'parent4';
    this.play = [1, 2, 3];
}
function Child4 () {
    Parent4.call(this);
    this.type = 'child4';
}
Child4.prototype = Parent4.prototype;
var s5 = new Child4();
var s6 = new Child4();
console.log(s5, s6);

console.log(s5 instanceof Child4, s5 instanceof Parent4);
console.log(s5.constructor);

組合繼承的優化2

function Parent5 () {
    this.name = 'parent5';
    this.play = [1, 2, 3];
}
function Child5 () {
    Parent5.call(this);
    this.type = 'child5';
}
Child5.prototype = Object.create(Parent5.prototype);

相關學習文章鏈接:
JS中原型對象的徹底理解:https://blog.csdn.net/u012468376/article/details/53121081
JS原型徹底理解2—繼承中的原型鏈:https://blog.csdn.net/u012468376/article/details/53127929

(本文純屬個人學習筆記,如有不足請留言!)

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章