简体   繁体   中英

Javascript What is best practice using IF or SWITCH or “dynamic function name” in this case

I am looking for a best practice in this hypothetical situation.

In the example below the function changeGallery0() is a unique function that is Not the same as changeGallery1(), changeGallery2(). They can not be modified to solve this. But each function does take the exact same data (newArrayData)

This code seems "ugly" but works properly. It would become more ugly with 20 galleries. I realize some of this problem exists with the calling unique functions, but it helps illustrate my question.

Using a SWITCH case seems to be more proper. But does it have any advantage over this IF based solution? It seems like a "dynamic function name" (does that exist) would make sense?

Thank you!

if (a == 0) changeGallery0(newArrayData);
if (a == 1) changeGallery1(newArrayData);
if (a == 2) changeGallery2(newArrayData);
if (a == 3) changeGallery3(newArrayData);

You could try something like this:

var fn = window['changeGallery' + a];
if (typeof fn === "function")  {
    fn.apply(null, newArrayData);
}

The first argument to "apply" would be "this" in your function call.

你可以做

window["changeGallery" + a](newArrayData);

I think it would be better to use a for loop. You can place functions inside an array.

var funcArray = [function1, function2 , function3, ...];

There is one thing you need to know about this that is how branching will occur with if else or switch.

  1. With if else if a is 0 the first one will be hit and then you miss rest of 3 but still need to check condition.
  2. With switch you will have branches done but actual code will have a break after one and not check rest of conditions.

You can achieve same with if by using else statements like if a is not 0 then check if its 1 otherwise no need to do so If a is not 1 then check if its 2 otherwise no need to do so this would create nested if else statements that are similar to a switch branching and switch would read better in code so use that.

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