[英]Combining two different JavaScript functions to get JSON sibling data
[英]Javascript combining different functions into one
假设我有一堆函数,比如
_computeValue(value1, value2) { //return some stuff } _computeIcon(value1, value3) { //return some stuff } _computeStyle(value2, value5, value1) { //return some stuff }
我想要的是将所有这些功能组合成一个这样的单一功能:
_compute(key, parameters){ if(key === 'style') { //return style function } if(key === 'Icon') { //return Icon function } ..... }
考虑到我传递了不同的值并需要在正确的地方使用它,最好的方法是什么。
从第二个代码块的外观来看, switch
语句可能是一个很好的解决方案。 例子:
_compute(key, parameters) {
switch(key) {
case 'style':
// style code
break;
case 'icon':
// icon code
break;
...
default: // optional
// none of the above
break;
}
将函数添加到对象,然后使用键调用它们:
const _compute = { style: function fn(...params) { return `style: ${params}`; }, icon: function (...params) { return `icon ${params}`; } }; console.log(_compute.style(1)); console.log(_compute.icon(1,2,3));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.