| 注册
请输入搜索内容

热门搜索

Java Linux MySQL PHP JavaScript Hibernate jQuery Nginx
jessehuang
7年前发布

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

   <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>    
 本文由用户 jessehuang 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
 转载本站原创文章,请注明出处,并保留原始链接、图片水印。
 本站是一个以用户分享为主的开源技术平台,欢迎各类分享!
 本文地址:https://www.open-open.com/lib/view/open1491094878762.html
面向对象编程 JavaScript开发 ECMAScript JavaScript