I'm having a issue with babel transpile down to ES5. For the majority of my application all other classes are compiled down correctly. One of the classes however has a problem. When it is transpiled, then none of the methods are present on the instances anymore.
When the class constructor is executed, it raises a exception:
Uncaught TypeError: this.basket.setCurrency is not a function
Here is the class.
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> ...
}
The class that it's extending, ItemSet
can be found in 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);
}
}
Finally, here is the code that is being generated by babel when it's transpiled, just pasting the relevant part for brevity:
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;
Last bit of background: I'm using polymer build
to do the transpiling
since my components are mostly polymer elements.
Does anyone know what may be causing this?
Turns out this is because es5 would not let you extend arrays. There are some workarounds which I found here: https://stackoverflow.com/a/46898347/433267
I've implemented this in basket-weaver
on a special es5-compat
branch.