在ES6代码中扩展EcmaScript 5类 [英] Extending EcmaScript 5 classes in ES6 code
问题描述
我想在一个新的项目中使用EcmaScript 6(通过Browserify和Babelify),但这取决于ES5中编写的第三方库。问题是在我的项目中创建子类,从子库中扩展。
I want to use EcmaScript 6 (via Browserify and Babelify) in a new project, but it depends on third party libraries written in ES5. The problem is creating subclasses in my project which extend from the ones in libraries.
例如:
// 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,首先构建父类的对象,然后将其附加到它:
This almost works except that Creature() constructor is not run. I devised a workaround/hack which constructs the parent class's object first and then appends stuff to it:
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;
}
}
这种方法似乎只要原来的类没有构造函数的功能。
This approach seems to work as long as the original class does not have "constructor" function.
我的问题是:在使用ES6的类时,是否扩展它们的最佳方法(除了要求库的作者迁移)?还是有更好的方法?我想在我的项目中继续使用class {}语法。
My question is: is that the best way of extending them when using ES6's classes (save from asking the library's author to migrate)? Or is there an even better way? I would like to keep using class {} syntax in my project.
推荐答案
您的解决方案使用babel正常工作。您的代码被编译成以下ES5代码。
Your solution works properly using babel. Your code gets compiled to the following ES5 code.
// 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);
。
As you can see from the above code, the constructor of the Creature
class is called correctly. Line _Creature.call(this, "fish");
.
我添加了以下代码来演示鱼是一个生物
以及 Fish
的实例。
I added the following code to demonstrate that fish is an instance of Creature
as well as an instance of Fish
.
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
这篇关于在ES6代码中扩展EcmaScript 5类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!