JavaScript使用ES6的Class面向對象繼承時 this is not defined 解決方法

傳統的JavaSCript繼承是這個樣子的:

//相當于構造函數
var myClass = function(name) {
    this._name = name;  
};

//通過原型方法繼承
myClass.prototype = {
    (...)
};

或者使用Node.JS的util對象繼承

util.inherits(myClass, require('events').EventEmitter);

現在ES6提供了一種新的類和構造函數實現方法:

class Character {
   constructor(name) {
      this._name = name;
   }
}

不過如果你使用了繼承就需要先調用 super() 函數,才能使用this,否則會報錯

class Hero extends Character{
  constructor(){
      super();  // 如果不調用super()則會報錯
      this._name = name;
  }
}

這些規則在ES2015中已經規定了,必須在子類中調用super,否則this無法使用。

  1. In a child class constructor,  this  cannot be used until  super  is called.
  2. ES6 class constructors MUST call  super  if they are subclasses, or they must explicitly return some object to take the place of the one that was not initialized.

相關文章

在JavaScript中創建命名空間的幾種寫法

深入理解JavaScrip面向對象和原型繼承

 

來自:http://ourjs.com/detail/58df73414edfe07ccdb23542

 

 本文由用戶 jessehuang 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!