javascript - 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 `- ${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);
您只需要设置您要设置的选项,一目了然更容易理解。
我想知道,有没有更好的方法呢?有小费吗?
谢谢!
解决方案
推荐阅读
- keras - 用于时间序列分析 keras 的 lstm 显示 numpy.ndarray 对象没有属性“_validate_or_infer_batch_size”
- python - 如何使用变量 .format 写入文件?
- qsplashscreen - QSplashScreen 不显示图像 pyqt5
- python - 需要用漂亮的汤找到价值
- php - 如何从 PHP 页面使用 Zoho CRM API V2?
- javascript - TypeScript - 将多个接口组合成一个
- python - Kubernetes部署内存占用高
- javascript - React DevTools 将组件显示为“正在加载...”
- asp.net-core - 复杂类——跨类实现
- nginx - nginx 提供静态 html 和代理