javascript繼承

引言

繼承的本質(zhì)是對(duì)原型鏈的操作,具體來(lái)說(shuō)有三種方式:
1.通過(guò)構(gòu)造函數(shù)實(shí)現(xiàn)
2.通過(guò)原型鏈實(shí)現(xiàn)
3.前面兩種方式的組合實(shí)現(xiàn)

代碼示例

function Rectangle(length,width){
    this.l = length;
    this.w = width;
}

Rectangle.prototype.getArea = function(){
    return this.l = this.w
}

function Square(length){
    Rectangle.call(this.length,length)
}

Square.prototype = Object.create(Rectangle.prototype,{
    constructor:{value:Square}
})

var square = new Square(3);
console.log(square.getArea());
console.log(square instanceof Square);
console.log(square instanceof Rectangle)

實(shí)現(xiàn)效果

繼承的實(shí)現(xiàn).png

代碼講解

為何第一個(gè)console.log是undefined但第二個(gè)console.log是true

這個(gè)主要是借用call 來(lái)改變this的指向,通過(guò) call 調(diào)用 Rectangle,此時(shí) Rectangle中的 this 是指 Square。有個(gè)缺點(diǎn),從打印結(jié)果看出 Square并沒(méi)有g(shù)etArea方法,所以這種只能繼承父類的實(shí)例屬性和方法,不能繼承原型屬性/方法。

第三個(gè)console.log為何是true

通常 prototype里面有一個(gè) constructor, 而我們此時(shí)子類的 prototype 指向是 父類的 prototye ,而父類prototype里面的contructor當(dāng)然是父類自己的。使用Object.create(),它的作用是將對(duì)象繼承到proto屬性上。這樣Square就繼承了Rectangle的prototype 。之所以要在Object.create()中重新寫(xiě)一個(gè)constructor,是因?yàn)椴粚?xiě)的話,constructor是指向Rectangle的,這樣square instanceof Rectangle的時(shí)候,會(huì)順著原型鏈找到Rectangle的constructor,所以需要新建一個(gè)constructor賦值給Square

最后編輯于
?著作權(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)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

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