babel将ES6转换为ES5时方法未定义

时间:2018-10-16 19:55:44

标签: polymer babel ecmascript-5 es6-class

我在将Babel转换到ES5时遇到问题。对于我的大多数 应用程序所有其他类均已正确编译。 但是,其中一个类存在问题。转译后,实例上不再存在任何方法。

执行类构造函数时,会引发异常:

Uncaught TypeError: this.basket.setCurrency is not a function

这是课程。

export class Basket extends ItemSet {
  static get currencies() {
    return [
      { code: 'gbp', symbol: '£', title: 'Pounds' },
      { code: 'usd', symbol: '$', title: 'US Dollars' },
      { code: 'eur', symbol: '€', title: 'Euros' }
    ];
  }

  constructor(currency, ...args) {
    super(...args);
    this.store = window.localStorage;
    this.setCurrency(currency);
    this.load();
  }

  setCurrency(code) {
    // Only set the currency if it's valid for our Basket
    Basket.currencies.forEach((currency) => {
      if (currency.code == code) {
        this.currency = currency;
        this.store.cxCurrency = JSON.stringify(this.currency);
      }
    });
  }

  ... <snip> ...

}

正在扩展的类ItemSet可以在basket-weaver中找到:

https://github.com/andrewebdev/basket-weaver/blob/master/src/items.js#L72-L80

export class ItemSet extends Array {

  getTotal(...args) {
    let subTotals = this.map(item => { return item.getTotal(...args); });
    if (!subTotals) throw "Cannot call getTotal() on an empty ItemSet";
    return sum(...subTotals);
  }

}

最后,这是babel正在生成的代码 转译,只是为了简洁而粘贴相关部分:

var Basket =
/*#__PURE__*/
function (_ItemSet3) {
  babelHelpers.inherits(Basket, _ItemSet3);

  function Basket() {
    babelHelpers.classCallCheck(this, Basket);
    return babelHelpers.possibleConstructorReturn(this, (Basket.__proto__ || Object.getPrototypeOf(Basket)).apply(this, arguments));
  }

  babelHelpers.createClass(Basket, [{
    key: "setCurrency",
    value: function setCurrency(code) {
      var _this7 = this;

      // Only set the currency if it's valid for our Basket
      Basket.currencies.forEach(function (currency) {
        if (currency.code == code) {
          _this7.currency = currency;
          _this7.store.cxCurrency = JSON.stringify(_this7.currency);
        }
      });
    }
  }, {
    ... <snip lots of other methods & properies> ...
  }]);
  return Basket;
}(_items.ItemSet);

_exports.Basket = Basket;

最后的背景:我正在使用polymer build进行转译 因为我的成分主要是聚合物元素。

有人知道这是什么原因吗?

1 个答案:

答案 0 :(得分:0)

事实证明这是因为es5不允许您扩展数组。我在这里找到了一些解决方法:https://stackoverflow.com/a/46898347/433267

我已经在basket-weaver的特殊es5-compat分支上实现了这一点。

相关问题