我很好奇,因为出现“未定义不是函数”错误。考虑以下类别:
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;
撇开重构,问题就在网上:this.currencyValidator(currencyObject);
我收到错误“未定义不是函数”
我认为这是因为我有一个静态方法,其内部调用了一个非静态方法?非静态方法必须是静态的吗?如果这样的话,this.methodName
仍然有效的概念仍然有效吗?
不可以,静态方法不能调用非静态方法。
考虑到您有对象a
和的b
两个实例Currency
。currencyValidator
存在于这两个对象上。现在store()
属于类Currency
本身,而不是这些对象之一。因此,在中Currency.store()
,它如何知道要调用的对象currencyValidator()
?简单的答案是,事实并非如此。这是使用静态方法的陷阱之一,也是人们经常反对使用静态方法的原因之一。
无论如何,你可以通过解决这个问题a
进入Currency.store()
,并调用a.currencyValidator()
来代替。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句