Joe wrote:
I have 3 functions: ClientInfoA is doing something
ClientInfoB is doing something
SelectFunction2Run is a function to determine which function needed
to run based on the value of the variable Method2Run. If the
clientType is A, it would run ClientInfoA function. If it is
clientType B, it would run the ClientInfoB function.
Only 2 types of client?
Based on the value of Method2Run,
how would I run the function dynamically? I know that there are many
ways not to do this. But I am creating this for easy maintenance.
<snip> function ClientInfoA ()
{
....
}
function ClientInfoB ()
{
....
}
Function SelectFunction2Run
^ ^^
An upper case - F - will not help. An arguments/parameters list and the
opening brace would probably also be a good idea.
var Method2Run
switch (clientType)
{
case "A": Method2Run = ClientInfoA
break;
case "B": Method2Run = ClientInfoB
break
}
Not having a -default: - in a switch statement is asking for trouble.
// how do I run the Method2Run????
Run Method2Run (whatever the value)
The literal answer would be:-
function SelectFunction2Run(){
var Method2Run
switch (clientType){
case "A": Method2Run = ClientInfoA;
break;
default: Method2Run = ClientInfoB;
break;
}
Method2Run();
}
But since - Method2Run - is a local variable and will go out of scope as
soon as the function exits you may as well just call one of the two
functions directly based on the - clientType - variable:-
function SelectFunction2Run(){
if(clientType == "A"){
ClientInfoA();
}else{
ClientInfoB();
}
}
- or slightly more compactly:-
function SelectFunction2Run(){
((clientType == "A")?ClientInfoA:ClientInfoB)();
}
But that leaves you calling - SelectFunction2Run - whenever you wanted
to call which ever of the two functions was to be used, and repeating
the test on each call. A more interesting approach is to define the
whole lot as one function, call that function each time you wanted the
facility but have the function re-configure itself on the first occasion
it was called. Thus subsequent testing is not necessary and code using
the function exclusively uses one identifier and has no idea that the
function re-configured itself the first time it was called (I am
assuming that - clientType - does not change while the script is
running):-
function callThisFunction(){
function ClInfoA(){
...
}
function ClInfoB(){
...
}
/* Replace this function with one of its two inner functions
so subsequent calls will execute that function directly
instead. And call whichever function is assigned as the
replacement so it can act for this initial function call:-
*/
(this.callThisFunction = ((clientType=="A")?ClInfoA:ClInfoB))();
}
Apart from the global - clientType - variable (which is almost certainly
a mistake and should be replaced with feature detection directly related
to the choice being made at this point), the result is self-contained,
easily portable and outwardly simple. All of which contribute towards
easy maintenance.
Richard.