js構(gòu)造函數(shù)+原型鏈 實(shí)現(xiàn)繼承

ES5形式

  function fun() {
    this.name = 'fun',
    this.arr = [1,2,3]
  }

  fun.prototype.myLog = function() {
    console.log(this.arr);
  }

  function cFun () {
    fun.call(this) //call調(diào)用父函數(shù) 繼承父函數(shù)的屬性
    this.type = 'child'
  }

  cFun.prototype = fun.prototype // 構(gòu)造函數(shù)的原型對(duì)象指向要繼承的父函數(shù)的原型對(duì)象
  cFun.prototype.constructor = cFun

  var c1 = new cFun()
  console.log(c1);
  c1.myLog()
  console.log(c1 instanceof cFun); // true
  console.log(f1 instanceof cFun); // true

執(zhí)行結(jié)果如圖:


image.png

缺點(diǎn):因?yàn)楦负瘮?shù)和子函數(shù)都是同一個(gè)對(duì)象,導(dǎo)致父函數(shù)和子函數(shù)的實(shí)例對(duì)象,在執(zhí)行instanceof時(shí),都為true 無(wú)法區(qū)分。
用Object.creacte(fun.prototype)創(chuàng)建中間對(duì)象的形式可以解決這個(gè)問(wèn)題

ES6形式

  class Teacher {
    constructor(name) {
        this.name = name
        this.age = 30
    }
    sayHi() {
        console.log(`hello everyone,我叫${this.name}`);
    }
  }

  class Student extends Teacher {
    constructor(name) {
        super(name)
        this.name = name
    }
    sayHello() {
        console.log(`大家好,我叫${this.name}`);
    }
  }

  const stu1 = new Student('張三')
  console.log(stu1);
  stu1.sayHello()
  stu1.sayHi()

結(jié)果如下:


image.png
?著作權(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ù)。

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

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