JavaScript原型繼承

JavaScript原型繼承

function A() {
    this.a = 'A'
}

A.prototype.showA = function () {
    console.log(this.a)
};

function B() {
    A.call(this);
    this.b = 'B'
}

B.prototype = Object.create(A.prototype);
B.prototype.constructor = B;    // 把B原型的構(gòu)造函數(shù)修復(fù)為B
B.prototype.showB = function () {
    console.log(this.b)
};

b = new B();
b.showA();
b.showB();
console.log('b instanceof B: ', b instanceof B);
console.log('b instanceof A: ', b instanceof A);


打印結(jié)果:

A
B
b instanceof B:  true
b instanceof A:  true

封裝可復(fù)用繼承函數(shù):

function inherit(parent, child) {
    child.prototype = Object.create(parent.prototype);
    child.prototype.constructor = child;
}

實(shí)現(xiàn)繼承:

function A(a) {
    this.a = a
}

A.prototype.showA = function () {
    console.log(this.a)
};

function B(a, b) {
    A.call(this, a);
    this.b = b
}

inherit(A, B);  // 繼承

B.prototype.showB = function () {
    console.log(this.b)
};

b = new B('aaa', 'bbb');
console.log(b.a);
console.log(b.b);
b.showA();
b.showB();
console.log('b instanceof B: ', b instanceof B);
console.log('b instanceof A: ', b instanceof A);

打印結(jié)果:

aaa
bbb
aaa
bbb
b instanceof B:  true
b instanceof A:  true

學(xué)習(xí)參考:
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Inheritance_and_the_prototype_chain
https://www.liaoxuefeng.com/wiki/1022910821149312/1023021997355072

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容