【发布时间】: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 `- ${formatted}`;
if (value > 0) return `+ ${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