leslie1943 / blog

Some front-end points and some interview questions.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

React: 构造函数(constructor)中的super()和super(props)

leslie1943 opened this issue · comments

1. 定义class组件,为什么要加上super()

class App extends Component{
    constructor(){
        // super()
        this.state = {name: 'su'} // ❌ 'this' is not allowed before super() => Reference Error
        this.handleChange = this.handleChange.bind(this)
    }
}

2. super的作用究竟是什么?

  • super关键字, 它指代父类的实例(也就是父类的this对象)
  • 子类必须在constructor函数中调用super方法, 否则新建实例时会报错.
  • 这是因为子类没有自己的this对象,而是继承自父类的this对象
  • 总而言之: 子类如果不在constructor()中调用super(),子类就得不到this对象

3. super() vs super(props)

  • 只有一个理由需要传递props作为super的参数,就是希望在构造函数中使用this.props