【问题标题】:Can static methods in javascript call non staticjavascript中的静态方法可以调用非静态的吗
【发布时间】:2016-01-27 02:07:45
【问题描述】:

我很好奇,因为我收到“未定义不是函数”错误。考虑以下类:

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

【问题讨论】:

  • 我想知道您为什么决定将store 设为静态,因为您似乎不知道static 的含义。
  • 当然,静态方法可以调用非静态方法当它有一个实例可以调用它时。你的实例在哪里?

标签: javascript class ecmascript-6 static-methods


【解决方案1】:

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

【讨论】:

  • ...除非静态方法获取一个(或多个)实例作为参数;或者当它自己构造一个实例时。当然,this 确实指的是类本身。
  • 我看不出这是一个“例外”,它仍然没有this
  • "...except" 是为了完成第一句关于“有意义”的句子。您确实不能使用this 从静态方法调用实例方法,但您可能不需要this
【解决方案2】:

不,一般静态方法不能调用实例方法。能够这样做是没有意义的。

唯一需要注意的是,没有什么可以阻止静态方法实例化类的实例,此时它可以以通常的方式调用实例方法。

【讨论】:

    【解决方案3】:

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

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

    无论如何,您可以通过将a 传递给Currency.store() 并改为调用a.currencyValidator() 来解决此问题。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-13
      • 1970-01-01
      • 2013-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多