Relative newbie to JS and node(though I don't think the fact that it's node matters, but just in case), but learning fast. Probably more detail in this question than needed to ask it, but I'm attempting to include in here some explanation of what I do and don't already understand, in case that's helpful context. I suspect there's something simple I'm missing here...
I have a class A with a bunch of (static, though I don't think that matters?) functions in it. They all do pretty specific things. I have another class B calling functions in A based on the desired function name and arguments being in variables in B.
I understand I could do something like this:
class A {
static doIt(theFunctionName, theArguments) {
if (theFunctionName == 'asdf') {
this.asdf(theArguments);
} else if (theFunctionName == 'qwer') {
this.qwer(theArguments);
} else if (theFunctionName == 'zxcv') {
this.zxcv(theArguments);
// } else if ( .. etc ...) {
// ... etc ...
} else {
//return some kind of error or whatever
}
}
static asdf(theArguments) {
//do stuff and return something
}
static qwer(theArguments) {
//do stuff and return something
}
static zxcv(theArguments) {
//do stuff and return something
}
}
class B {
constructor(...) {
this.theFunctionName = ...;
this.theArguments = [...];
}
myResult = A.doIt(this.theFunctionName, this.theArguments);
}
Further, I understand I can access properties of an object dynamically:
obj[myKey] = something;
or
myResult = obj[key]
But functions?
I believe I'm looking for some way to do the latter with functions not just properties - some way to do the functions stuff more dynamically without all the if ... else if ... ?
I understand functions are first class in JS, and can be passed around like objects. But I'm not sure that helps here since I'm not passing the functions themselves, I'm choosing a function to call based on its name and arguments in variables... right?
I've tried a couple of things attempting to use the principles from the properties examples with functions but not getting the desired results. I'm guessing either this really can't be done (without all the if... else if... ... or I'm missing something simple.
Any help greatly appreciated. Thanks!