JavaScript中的静态方法可以调用非静态方法>>

问题描述 投票:5回答:4

我很好奇,因为出现了“未定义不是函数”错误。考虑下面的类:

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的概念是否仍然有效?

我很好奇,因为出现了“未定义不是函数”错误。请考虑以下类:var FlareError = require('../ flare_error.js');类Currency {构造函数(this._currencyStore = ...

javascript class ecmascript-6 static-methods
4个回答
12
投票

否,静态方法不能调用非静态方法。


2
投票

以任何语言从静态函数中调用非静态函数都是没有意义的。静态(在这种情况下)意味着它基本上在对象之外,除了名称外,其他都无关。它不绑定任何实例,因此没有thisself来调用非静态(即成员)字段。


1
投票

否,通常静态方法不能调用实例方法。这样做是没有意义的。


-1
投票

您需要实例化静态方法中的类以使用非静态方法。下面的示例定义了静态的“ from”方法,并通过实例化“ Group”类使用了非静态的“ add”方法。

© www.soinside.com 2019 - 2024. All rights reserved.