mercredi 19 août 2015

javascript polymorphism refactoring

I have an object that maps properties to functions, something like this:

var objFunctions = {
  prop1: func1,
  prop2: func2,
  prop3: func3,
};

Now, I just need a valid prop name to call the adequate function, for example

   var callFuncProp = 'prop1'
    objFunctions[callFuncProp]('value1');

This works fine, however, let's say that a new function came up, and that needs additional arguments. Dynamically calling this function with additional arguments means that all other functions would receive them

objFunctions[callFuncProp]('value1', 'value2', 'value3'); 
// calls func1 which defined only one parameter

This also works, but I really have a problem with this kind of design. How could I refactor the code so that I can still dynamically call the functions but pass only additional arguments to the functions that really expects them ? I would really like to avoid switch statement...

Aucun commentaire:

Enregistrer un commentaire