【发布时间】:2016-02-03 09:00:43
【问题描述】:
我想在一个新项目中使用 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() 构造函数。我设计了一种解决方法/hack,它首先构造父类的对象,然后将内容附加到它:
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;
}
}
只要原始类没有“构造函数”功能,这种方法似乎就可以工作。
我的问题是:这是在使用 ES6 的类时扩展它们的最佳方式(除了要求库的作者进行迁移)吗?还是有更好的方法?我想在我的项目中继续使用 class {} 语法。
【问题讨论】:
-
Babel 依赖于 ES5 类正确设置 'Creature.prototype.constructor = Creature `,也许你没有正确地这样做?如果父类是绝对基类,这应该会自动发生,但如果父类有自己的父类,则它可能有错误的“.constructor”。