【问题标题】:OO JavaScript, how do I improve this Class? Is there a better, cleaner way of doing it?OO JavaScript,我该如何改进这个类?有没有更好、更清洁的方法呢?
【发布时间】:2018-10-25 16:30:26
【问题描述】:

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

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);

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

我想知道,有没有更好的方法呢?有什么建议吗?

谢谢!

【问题讨论】:

  • 一种常见的方法是使用和选项对象并将其传递给构造函数new Amount({currency, format, somethingElse: true})
  • 一旦你传递了 3-4 个参数,人们通常会使用一个对象,因此你可以添加任意数量的参数,而无需更改函数签名。那么可以使用解构来轻松将该对象转换回单独的变量。
  • 这是一种选择,好像,谢谢
  • 在构造函数中初始化你的属性,不要依赖 setter 来定义它们。
  • 看起来你根本不需要class。没有什么需要具有多个方法或 OOP 状态的实例。只需编写一个普通函数并使用options object argument

标签: javascript oop


【解决方案1】:

我认为最好将参数作为 Object,{value:val, currency:cur...} 传递。 并在构造函数中使用默认配置来减少使用此类时要输入的参数数量。

这是一个具有一个属性的示例,您可以对其他属性执行相同操作

class Amount {
    constructor(opt){
      const defaultOpts= {currency:'$'}
      this.opts=Object.assign(defaultOpts,opt)
    }
    
    getValueWithCurruency(){
      return this.opts.value+this.opts.currency
    }
    
}
    
const foo= new Amount({value:50})    
console.log(foo.getValueWithCurruency())//50$

const fooEuro= new Amount({value:50,currency:"€"})  
console.log(fooEuro.getValueWithCurruency())//50€

【讨论】:

    猜你喜欢
    • 2012-07-08
    • 1970-01-01
    • 2019-01-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 2023-03-21
    相关资源
    最近更新 更多