【问题标题】:Extending EcmaScript 5 classes in ES6 code在 ES6 代码中扩展 EcmaScript 5 类
【发布时间】: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”。

标签: javascript ecmascript-6


【解决方案1】:

您的解决方案使用 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 link

我添加了以下代码来证明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);

输出:

fish
test
true
true

【讨论】:

    【解决方案2】:

    ES5 构造函数和 ES6 类可以无缝地存在于继承链中。如果您在运行之前使用 Babel 之类的工具将代码转换为 ES5,您可以看到它全部转换为基于原型的继承。请看这个例子here,它在三个层次的继承链中同时具有类和构造函数。希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2019-11-18
      • 2019-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-02
      • 1970-01-01
      • 2018-02-26
      • 2020-04-28
      相关资源
      最近更新 更多