javascript中的静态方法可以非静态调用

The*_*ebs 5 javascript static-methods class ecmascript-6

我很好奇,因为我得到"未定义不是函数"错误.考虑以下课程:

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;
Run Code Online (Sandbox Code Playgroud)

除了重构,问题就出现了:this.currencyValidator(currencyObject);我得到错误"undefined is not a function"

我假设这是因为我有一个静态方法谁的内部调用非静态方法?这种非静态方法必须是静态的吗?如果是这样的话this.methodName仍然有用吗?

Jos*_*sch 12

不,静态方法不能调用非静态方法.

考虑一下你有对象ab两个实例Currency.currencyValidator存在于这两个对象上.现在store()属于类Currency本身,而不属于那些对象之一.所以,在Currency.store(),它如何知道要调用哪个对象currencyValidator()?简单的答案是它不是,所以它不能.这是使用静态方法的一个缺陷,也是人们经常反对它们的原因之一.

无论如何,你可以通过解决这个问题a进入Currency.store(),并调用a.currencyValidator()来代替.


Bli*_*ndy 6

在任何语言中,从静态函数调用非静态函数都是没有意义的。静态(在此上下文中)意味着它基本上位于对象之外,除了名称之外,其他方面都是独立的。它不绑定到任何实例,因此没有thisself可以调用非静态(即成员)字段。