class - Can static methods in javascript call non static -
i curious "undefined not function" error. consider following class:
var flareerror = require('../flare_error.js'); class currency { constructor() { this._currencystore = []; } static store(currency) { (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 name attribute in json.'); } if (!currencyjson.hasownproperty('description')) { flareerror.error('currency must have description attribute in json.'); } if (!currencyjson.hasownproperty('icon')) { flareerror.error('currency must have icon attribute in json.'); } } static getcurrencystore() { return this._currencystore; } }; module.exports = currency;
refactoring aside, issue on line: this.currencyvalidator(currencyobject);
error "undefined not function"
i assume because have static method who's internals call non static method? non static method have static? , if concept of this.methodname
still work?
no, static method cannot call non-static method.
consider have objects a
, b
, both instances of currency
. currencyvalidator
exists on 2 objects. store()
belongs class currency
itself, not 1 of objects. so, in currency.store()
, how know object call currencyvalidator()
on? simple answer doesn't can't. 1 of pitfalls of using static methods , 1 of reasons people urge against them.
regardless, can around passing a
currency.store()
, , calling a.currencyvalidator()
instead.
Comments
Post a Comment