JavaScript使用ES6的Class面向对象继承时 this is not defined 解决方法

jessehuang 2年前
   <p>传统的JavaSCript继承是这个样子的:</p>    <pre>  <code class="language-javascript">//相当于构造函数  var myClass = function(name) {      this._name = name;    };    //通过原型方法继承  myClass.prototype = {      (...)  };</code></pre>    <p>或者使用Node.JS的util对象继承</p>    <pre>  <code class="language-javascript">util.inherits(myClass, require('events').EventEmitter);</code></pre>    <p>现在ES6提供了一种新的类和构造函数实现方法:</p>    <pre>  <code class="language-javascript">class Character {     constructor(name) {        this._name = name;     }  }</code></pre>    <p>不过如果你使用了继承就需要先调用 super() 函数,才能使用this,否则会报错</p>    <pre>  <code class="language-javascript">class Hero extends Character{    constructor(){        super();  // 如果不调用super()则会报错        this._name = name;    }  }</code></pre>    <p>这些规则在ES2015中已经规定了,必须在子类中调用super,否则this无法使用。</p>    <ol>     <li>In a child class constructor,  this  cannot be used until  super  is called.</li>     <li>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.</li>    </ol>    <p>相关文章</p>    <p><a href="/misc/goto?guid=4959746569221057534" rel="nofollow,noindex">在JavaScript中创建命名空间的几种写法</a></p>    <p><a href="/misc/goto?guid=4959746569310020882" rel="nofollow,noindex">深入理解JavaScrip面向对象和原型继承</a></p>    <p> </p>    <p>来自:http://ourjs.com/detail/58df73414edfe07ccdb23542</p>    <p> </p>