在ES6代码中扩展EcmaScript 5类

10

我想在一个新项目中使用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 {}语法。


1
Babel 依赖于 ES5 类适当设置 'Creature.prototype.constructor = Creature',也许您没有正确地执行这个步骤?如果父类是绝对的基础,则应该自动发生,但如果父类有其自己的父级,则可能具有错误的 '.constructor'。 - loganfsmyth
1
你发布的示例代码在浏览器和Node.js中都可以正确运行,尚未编译。如果转译后不起作用,则可能是由于某个转译器中存在错误。 - cpcallen
2个回答

3
您的解决方案使用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");行。

Babel链接

我添加了以下代码以证明fishCreature的实例,也是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

0

ES5 构造函数和 ES6 类可以在继承链中无缝共存。如果您使用 Babel 等工具将代码转译为 ES5,然后再运行,您会发现它全部都被转换为基于原型的继承。请查看这个 示例,其中包含三级继承链中的类和构造函数。希望这能帮到您。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接