React(2) --super關鍵字

參考:http://www.phonegap100.com/thread-4911-1-1.htmlhtml

Es6中的super能夠用在類的繼承中,super關鍵字,它指代父類的實例(即父類的this對象)。子類必須在constructor方法中調用super方法,不然新建實例時會報錯。這是由於子類沒有本身的this對象,而是繼承父類的this對象,而後對其進行加工。若是不調用super方法,子類就得不到this對象。函數

    class Person {
          constructor (name) {
                this.name = name;
          }
    }

    class Student extends Person {
          constructor (name, age) {
                super(); // 用在構造函數中,必須在使用this以前調用
                this.age = age;
          }
    }

爲何官方的列子裏面寫個super(props):學習


只有一個理由須要傳遞props做爲super()的參數,那就是你須要在構造函數內使用this.propsthis

那官方提供學習的例子中都是寫成super(props),因此說寫成super(props)是徹底沒問題的,也建議就直接這樣寫。spa

相關文章
相關標籤/搜索