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 去调用子类的方法了。

本是前端小彩笔,摸索爬行,有理解不对的地方还请各路大神纠正。

原文地址:https://www.cnblogs.com/leolovexx/p/15351747.html