javascript中的静态方法可以非静态调用 [英] Can static methods in javascript call non static

查看:112
本文介绍了javascript中的静态方法可以非静态调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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;

重构除外,问题在于: this.currencyValidator(currencyObject) ); 我收到错误未定义不是函数

Refactoring aside, the issue is on the line: this.currencyValidator(currencyObject); I get the error "undefined is not a function"

我认为这是因为我有一个静态方法,其内部调用非静态方法?这种非静态方法必须是静态的吗?如果是这样, this.methodName 的概念是否仍然有效?

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?

推荐答案

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

No, a static method cannot call a non-static method.

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

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.

无论如何,你可以通过传递 a 进入 Currency.store(),并调用 a.currencyValidator()代替。

Regardless, you can get around this by passing a into Currency.store(), and calling a.currencyValidator() instead.

这篇关于javascript中的静态方法可以非静态调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆