Javascript 在ES6代码中扩展EcmaScript 5类
我想在一个新项目中使用EcmaScript 6(通过Browserify和Babelify),但它依赖于用ES5编写的第三方库。问题是在我的项目中创建从库中扩展的子类 例如: 这几乎可以正常工作,只是bioture()构造函数没有运行。我设计了一种变通/破解方法,它首先构造父类的对象,然后向其添加内容:Javascript 在ES6代码中扩展EcmaScript 5类,javascript,ecmascript-6,Javascript,Ecmascript 6,我想在一个新项目中使用EcmaScript 6(通过Browserify和Babelify),但它依赖于用ES5编写的第三方库。问题是在我的项目中创建从库中扩展的子类 例如: 这几乎可以正常工作,只是bioture()构造函数没有运行。我设计了一种变通/破解方法,它首先构造父类的对象,然后向其添加内容: class Fish extends Creature { constructor(name) { super("throw away"); //have to have this
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类时扩展它们的最佳方法吗(除了要求库作者迁移之外)?还是有更好的办法?我希望在我的项目中继续使用类{}语法。您的解决方案可以使用babel正常工作。您的代码将编译为以下ES5代码
// Library written in ES5
"use strict";
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) subClass.__proto__ = superClass; }
function Creature(type) {
this.type = type;
}
// my code in ES6
var Fish = (function (_Creature) {
function Fish(name) {
_classCallCheck(this, Fish);
_Creature.call(this, "fish");
this.name = name;
}
_inherits(Fish, _Creature);
return Fish;
})(Creature);
从上面的代码可以看出,生物
类的构造函数被正确调用。行<代码>\u生物。呼叫(这是“鱼”)代码>
我添加了下面的代码来证明鱼是生物的一个实例
,也是鱼的一个实例
var fish = new Fish("test");
console.log(fish.type);
console.log(fish.name);
console.log( fish instanceof Creature );
console.log( fish instanceof Fish);
输出:
fish
test
true
true
ES5构造函数和ES6类可以无缝地存在于继承链中。如果您在运行之前使用诸如之类的工具将代码传输到ES5中,您可以看到所有代码都转换为基于原型的继承。请看这个例子,它在继承链的三个层次上都有类和构造函数。希望这能有所帮助。Babel依赖ES5类正确设置'bioture.prototype.constructor=bioture',也许您没有正确设置?如果父类是绝对基,则应该自动执行,但如果父类有自己的父类,则可能有错误的“.constructor”。
fish
test
true
true