Can static methods in javascript call non static

爱⌒轻易说出口 提交于 2020-01-02 04:15:09

问题


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?


回答1:


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.




回答2:


It makes no sense to call a non-static function from a static one, in any language. Static (in this context) means that it's basically outside of the object, independent in all but name. It's not tied to any instance and thus there's no this or self to call non-static (ie member) fields.




回答3:


No, in general static methods cannot call instance methods. It makes little sense to be able to do so.

The only caveat is that there is nothing stopping a static method instantiating an instance of a class, at which point it can call the instance methods in the usual way.



来源:https://stackoverflow.com/questions/33371776/can-static-methods-in-javascript-call-non-static

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!