我想在新项目中使用 EcmaScript 6(通过 Browserify 和 Babelify),但它依赖于用 ES5 编写的第三方库。问题是在我的项目中创建从库中的子类扩展的子类。
E.g:
// 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;
}
}
只要原始类没有“构造函数”函数,这种方法似乎就有效。
我的问题是:这是使用 ES6 的类时扩展它们的最佳方式吗(无需要求库的作者迁移)?或者还有更好的方法吗?我想在我的项目中继续使用 class {} 语法。
您的解决方案使用 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);
从上面的代码可以看出,构造函数Creature
类被正确调用。线_Creature.call(this, "fish");
.
我添加了以下代码来演示fish是一个实例Creature
以及一个实例Fish
.
var fish = new Fish("test");
console.log(fish.type);
console.log(fish.name);
console.log( fish instanceof Creature );
console.log( fish instanceof Fish);
Output:
fish
test
true
true
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)