js原型繼承和構(gòu)造函數(shù)繼承

// 先看下原型繼承的實(shí)現(xiàn)方式

function Parent() {
  this.name = 'zhang san'
}
Parent.prototype.getName = function() {
  console.log(this.name)
}
function Child() {

}

Child.prototype = new Parent()
var child1 = new Child()
child1.getName()  // zhang san  

Child.prototype 是Parent的實(shí)例化子對象
Child 構(gòu)造函數(shù)就擁有了 this.name = 'zhang san ' 和
getName 方法
child1 是Child的實(shí)例化子對象, 故能繼承Child 的屬性和方法

// 下面是構(gòu)造函數(shù)繼承

  function Parent () {
   this.name =['jony', 'tom']
 }
  Parent.prototype.getName = function() {
    console.log (this.name)
  }

  function Child () {
     Parent.call(this)

// 此處借助call 來用Parent的方法和屬性
// 補(bǔ)充: apply 和call 的區(qū)別,   apply(this, [arr]) , 第二個(gè)參數(shù)是數(shù)組形式   call 的第二個(gè)參數(shù)是單個(gè)值.
 }

var child1 = new Child()
child1.name.push('lily')
console.log(child1.name)  //["jony", "tom", "lily"]  
var child2 = new Child() 
console.log(child2.name)   //  ) ["jony", "tom"]
 1,prototype可以動(dòng)態(tài)的給對象增加屬性和方法
2,可以實(shí)現(xiàn)子類繼承父類,擁有父類的屬性和方法
3,call和apply的區(qū)別,在于參數(shù)。
4,call和apply,可以膚淺理解為在子運(yùn)行環(huán)境中執(zhí)行父類的方法和屬性。
5,call和apply可以實(shí)現(xiàn)多繼承,一個(gè)子類可以繼承多個(gè)父類,但是prototype只能有有一個(gè)父類**
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

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