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.
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值