我想在一个新项目中使用EcmaScript 6(通过Browserify和Babelify),但是它依赖于用ES5编写的第三方库。问题在于如何在我的项目中创建从库中继承的子类。
例如:
// Library written in ES5
function Creature(type) {
this.type = type;
}
// my code in ES6
class Fish extends Creature {
constructor(name) {
super("fish");
this.name = name;
}
}
这个方法几乎可行,但 Creature() 构造函数并没有被执行。我想出了一种解决办法/黑科技,先构造父类对象,然后再向其中添加东西:
class Fish extends Creature {
constructor(name) {
super("throw away"); //have to have this or it wont compile
let obj = new Creature("fish");
obj.name = name;
return obj;
}
}
只要原始类没有“constructor”函数,这种方法似乎是有效的。
我的问题是:在使用ES6的类时,这是最好的扩展方式吗(不询问库的作者进行迁移)?还有更好的方法吗?我想在我的项目中继续使用class {}语法。