Методы не определены, когда Babel перевез ES6 в ES5 - PullRequest
0 голосов
/ 16 октября 2018

У меня проблема с трансплантацией 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 голосов
/ 23 октября 2018

Оказывается, это потому, что es5 не позволит вам расширять массивы.Вот некоторые обходные пути, которые я нашел здесь: https://stackoverflow.com/a/46898347/433267

Я реализовал это в basket-weaver в специальной es5-compat ветви.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...