引言
繼承的本質(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