I am curious as I get a "undefined is not a function" error. Consider the following class:
var FlareError = require('../flare_error.js');
class Currency {
constructor() {
this._currencyStore = [];
}
static store(currency) {
for (var key in currency) {
if (currency.hasOwnProperty(key) && currency[key] !== "") {
if (Object.keys(JSON.parse(currency[key])).length > 0) {
var currencyObject = JSON.parse(currency[key]);
this.currencyValidator(currencyObject);
currencyObject["current_amount"] = 0;
this._currencyStore.push(currencyObject);
}
}
}
}
currencyValidator(currencyJson) {
if (!currencyJson.hasOwnProperty('name')) {
FlareError.error('Currency must have a name attribute in the json.');
}
if (!currencyJson.hasOwnProperty('description')) {
FlareError.error('Currency must have a description attribute in the json.');
}
if (!currencyJson.hasOwnProperty('icon')) {
FlareError.error('Currency must have a icon attribute in the json.');
}
}
static getCurrencyStore() {
return this._currencyStore;
}
};
module.exports = Currency;
Refactoring aside, the issue is on the line: this.currencyValidator(currencyObject);
I get the error "undefined is not a function"
I assume this is because I have a static method who's internals call a non static method? Would that non static method have to be static? and if so does the concept of this.methodName
still work?
No, a static method cannot call a non-static method.
Consider that you have objects a
and b
, both instances of Currency
. currencyValidator
exists on those two objects. Now store()
belongs to the class Currency
itself, not one of those objects. So, in Currency.store()
, how does it know which object to call currencyValidator()
on? The simple answer is it doesn't so it can't. This is one of the pitfalls of using static methods and one of the reasons people often urge against them.
Regardless, you can get around this by passing a
into Currency.store()
, and calling a.currencyValidator()
instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With