简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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