原型鏈實(shí)現(xiàn)集繼承
function father(){
this.val=1;
this.arr=[1]
}
function son(){}
son.prototype=new father
var son1=new son()
var son2=new son()
son1.val=2
son2.varl //1
son1.arr.push(2)
son2.arr //[1,2]
上面的代碼實(shí)現(xiàn)原型鏈繼承最重要的son.prototype=new father
原型鏈繼承的優(yōu)點(diǎn)和缺點(diǎn):
優(yōu)點(diǎn):實(shí)現(xiàn)容易,操作簡單
缺點(diǎn):來自原型對象的引用屬性是所有實(shí)例都共享的,
另一個(gè)缺點(diǎn)就是 無法通過子類構(gòu)造器向父類傳參
構(gòu)造器函數(shù)實(shí)現(xiàn)繼承
function father(val){
this.val=val
this.arr=arr;
this.fun=function(){}
}
function son (val){
father.call(this,val)
}
var son1=new son(1)
var son2=new son(2)
核心:借用父類的構(gòu)造器來增強(qiáng)子類的實(shí)例,相當(dāng)于把父類的實(shí)例屬性復(fù)制一給子類裝上(完全沒有用到原型)
優(yōu)點(diǎn):解決了子類共享父類引用書屬性的問題
子類構(gòu)造器能夠向父類構(gòu)造器傳參
缺點(diǎn):無法實(shí)現(xiàn)函數(shù)的復(fù)用,每個(gè)子類實(shí)例都有一個(gè)自己的方法,太多了影響性能
組合發(fā)方式實(shí)現(xiàn)繼承
function super(){
this.val=2
this.arr=[2]
}
super.prototype.fun=function(){}
function sub(){
father.call(this)
}
sub.prototype=new super
var sub1=new sub()
var sub2=new sub()
核心:把實(shí)例函數(shù)都放在原型對象上,以實(shí)現(xiàn)函數(shù)復(fù)用。同時(shí)還要保留借用構(gòu)造函數(shù)方式的優(yōu)點(diǎn),通過Super.call(this);繼承父類的基本屬性和引用屬性并保留能傳參的優(yōu)點(diǎn);通過Sub.prototype = new Super();繼承父類函數(shù),實(shí)現(xiàn)函數(shù)復(fù)用
優(yōu)點(diǎn):不存在子類實(shí)例共享父類引用屬性的問題
可傳參
函數(shù)可復(fù)用
缺點(diǎn): 父類構(gòu)造器被實(shí)例化兩次,浪費(fèi)內(nèi)存