首页 > 解决方案 > OO JavaScript,我该如何改进这个类?有没有更好、更清洁的方法呢?

问题描述

我有一个函数,可以接受多个参数。

function formatString(Number, option1, option2, option3, option4, option5) {
  // apply options to the string:
  // eg: format to '0.00', append "+", append £ sign etc
  // return formatted Number as String
}

所有选项都是可选的,所以它开始变得有点难以使用和理解它的作用:

formatString(value, null, true, currency, null, true) // thats bad

所以我开始思考如何让它更易于使用、扩展和理解。我想出了一个类:

export default class Amount {
  constructor(value) {
    this.value = value;
  }

  set coin(val) {
    this._coin = val;
  }

  set currency(val) {
    this._currency = val;
  }

  set format(format) {
    this._format = format;
  }

  set withCurrencySymbol(val) {
    this._withCurrencySymbol = val;
  }

  set prependPlusOrMinus(val) {
    this._prependPlusOrMinus = val;
  }

  get formatted() {
    let { value } = this;
    if (this._coin && this._currency) {
      value = this.coinToCurrency(this.value, this._coin, this._currency);
    }

    let formatted = `${numeral(Math.abs(value)).format(this._format)}`;
    if (this._currency) formatted = `${currencySymbols[this._currency]}${formatted}`;

    if (this._prependPlusOrMinus) {
      if (value < 0) return `&#45; ${formatted}`;
      if (value > 0) return `&#43; ${formatted}`;
    }

    return formatted;
  }

  coinToCurrency() {
    const { rate } = exchangeRates[this._coin].find(item => item.currency === this._currency);
    return this.value * rate;
  }
}

它使使用更容易:

  const amount = new Amount(value);
  amount.currency = currency;
  amount.format = format;
  console.log(amount.formatted);

您只需要设置您要设置的选项,一目了然更容易理解。

我想知道,有没有更好的方法呢?有小费吗?

谢谢!

标签: javascriptoop

解决方案



推荐阅读