传统的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无法使用。
- In a child class constructor,
this
cannot be used untilsuper
is called. - 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.
相关文章
回复 (0)
微信扫码 立即评论