简体   繁体   English

Javascript将不同的功能合二为一

[英]Javascript combining different functions into one

let's say I have a bunch of functions like假设我有一堆函数,比如

 _computeValue(value1, value2) { //return some stuff } _computeIcon(value1, value3) { //return some stuff } _computeStyle(value2, value5, value1) { //return some stuff }

What I want is to combine all this functions into a single one like this:我想要的是将所有这些功能组合成一个这样的单一功能:

 _compute(key, parameters){ if(key === 'style') { //return style function } if(key === 'Icon') { //return Icon function } ..... }

What would be the best way to do it, considering I pass different value and need to use it in the right place..考虑到我传递了不同的值并需要在正确的地方使用它,最好的方法是什么。

By the looks of your second code block, a switch statement would likely be a good solution.从第二个代码块的外观来看, switch语句可能是一个很好的解决方案。 Example:例子:

_compute(key, parameters) {

  switch(key) {
    case 'style':
      // style code
      break;

    case 'icon':
      // icon code
      break;

    ...

    default: // optional
      // none of the above
      break;
}

Add the functions to an object and then call them using the key:将函数添加到对象,然后使用键调用它们:

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM