views:

47

answers:

2

Hi all,

How to solve huge hierarchy in JavaScript function? With Switch? Thank you.

(Sorry, I am not native English speaker.)

function do(param1, param2) {

  switch(param1) {

    case "write":

      /* another switch for param2 */

    break;

    ...

  }

}

Example calls:

do('write','house'); // write house
do('return','house'); // return house 
etc.
+1  A: 
function do(param1, param2) {
  switch(param1) {
    case "write":
    {
        writeFunction(param2);
        break;
    }
    case "return":
    {
        //This doesn't make sense, as the calling function would get the return message from the do function, but it wouldn't return it.
    }
  }
}

This is a bad way to program [bad programming practice]. I highly recommend you learn the language instead of defining your own functions to do one-line things...

I believe that "do" is a keyword reserved by JavaScript. I seldom use that keyword in every language. I recommend you stray away from it, either way.

ItzWarty
A: 

Create an object that names functions the way you want:

var obj = {
    "write": function(param) {
        //Write param
    },
    "return": function(param) { //Enclosing the function name is quotes lets you use reserved words as function names
        //Return param
    }
};

You could write your function to simply look up the members in that object using array notation:

function do(param1, param2) {
    obj[param1](param2);
}

Doing it this way would be much easier to maintain and would be much more scalable. However, I wouldn't even do it that way. I'd replace the do function with the object itself and then you could simply call these members the old fashioned way:

obj.write("Something");

Or, if the name return causes problems and you really want to use it:

obj["return"]("Something");

There's alot of power and flexibility in JavaScript objects and functions.

Bob
This is excatly what I was looking for! Thank you!
Bambert