开发者

Function hierarchy

开发者 https://www.devze.com 2022-12-20 19:02 出处:网络
How to solve huge hierarchy in JavaScript function? With Switch? Thank you. (Sorry, I am not native English speaker.)

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

(Sorry, I am not native English speaker.)

function do(pa开发者_如何转开发ram1, param2) {

  switch(param1) {

    case "write":

      /* another switch for param2 */

    break;

    ...

  }

}

Example calls:

do('write','house'); // write house
do('return','house'); // return house 
etc.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消