Class 中 繼承 父類 的時候,this 指向 淺析


 前言: 樓主在REACT中 寫 組件的時候,發現一個case. 

     class  Son  extends Father {}. 這類例子的時候, 在father  中,任何一個地方調用this, this 都可以訪問到son中的方法, 

    一下子有些驚到, ARE U kidding ME? 不是一直說 繼承中 , 父類不能訪問子類的訪問, 只能子類訪問父類的 方法嗎???

    這些的年的讀簡直白讀了,越想越想不通,樓主做了下列實驗 來分析一下 這個this. 到底咋回事, 真的 不看不知道,一看還真有點東西呢?

 

想不通 那就動手干。 寫了如下例子

class father {
  constructor(props) {
    console.log(this)
  }
  F_say() {
    console.log("i am. Father ")

  }
  F_send() {
    console.log("i am F_sned")
    this.son_send()
  }

}
class son extends father {
  constructor(props) {
    super(props)
  }
  son_say() {
    console.log("i am son ")

  }
  son_send = () => { console.log("son send") }
}

var one = new son();

 

簡單的例子, 在fatehr 中 打印的this.。

都知道 class 中。箭頭函數的作用 就等於 在 

constructor(props) {
    console.log(this)
    this.son_send=this.son_send.bind(this)
  }

 

1.在Father中 this 是可以訪問 son的 son_send的

2.子類中,可以看到 箭頭函數直接掛在到了 實例的屬性上,非箭頭函數 是掛在prototype上的

結果如下:

 

 

 

接下來,我們再把Father 中的函數 改為箭頭函數,看下掛在在哪里的,

class father {
  constructor(props) {
    console.log(this)
  }
  F_say() {
    console.log("i am. Father ")

  }
  F_send=()=> {
    console.log("i am F_sned")
    this.son_send()
  }

}
class son extends father {
  constructor(props) {
    super(props)
  }
  son_say() {
    console.log("i am son ")

  }
  son_send = () => { console.log("son send") }
}

var one = new son();
View Code

 

 

 F_send 直接掛到了實例屬性上。 足上,可以看到 在father中的this, 都是指向實例對象的。 其實也不難理解。

可以看到。在子類中 ES6要求必須super(props),這個的意思就是繼承父類的所有屬性。 相當於 父類的屬性 直接掛在this  實例對象上, 無論是father 還是son ,

constructor中的this 都是指向實例對象的。 PS:在son 中 可以使用this.F_send() 調用父類的方法,但是 不支持super.F_send()調用(super指向父類的原型對象,只能調用父類的屬性和方法)
  constructor(props) {
    super(props)
  }

 

 整個father 的所有箭頭函數 和constructor 中聲明的屬性均被掛在了 實例對象上。

 

關於react 組件 對於箭頭函數的說明 :

綜上, 也就很好理解了為什么可以在父類的方法中通過this 去調用子類的方法了。

 

本是前端小彩筆,摸索爬行,有理解不對的地方還請各路大神糾正。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM