I have method a()
, method b()
, and method c()
. I will get a response message from server, which contains a
or b
or c
and so on.
If the response message is a
, then I need to call method a()
.
If the response message is b
, then I need to call method b()
And so on...
I don't want to write any if else conditions or switch case to identify the method.
I don't want to do this:
if(res == 'a')
a();
else if(res == 'b')
b();
Instead of that I need something like reflections in Java.
I have method a()
, method b()
, and method c()
. I will get a response message from server, which contains a
or b
or c
and so on.
If the response message is a
, then I need to call method a()
.
If the response message is b
, then I need to call method b()
And so on...
I don't want to write any if else conditions or switch case to identify the method.
I don't want to do this:
if(res == 'a')
a();
else if(res == 'b')
b();
Instead of that I need something like reflections in Java.
Share Improve this question edited Nov 10, 2022 at 13:44 Dave Mackey 4,43221 gold badges83 silver badges144 bronze badges asked Jan 24, 2017 at 9:10 PrasathPrasath 1,2842 gold badges16 silver badges38 bronze badges3 Answers
Reset to default 8If you have defined the function in Global/window Scope then you can directly use res
variable
window[res]();
Otherwise define the function in object and then use it
var obj = {
a : function(){},
b : function(){}
}
obj[res]();
You could use an object and store the function inside, like
var functions = {
a: function () {},
b: function () {},
c: function () {}
default: function () {} // fall back
}
Usage:
functions[res]();
Or with default
(functions[res] || functions.default)();
For this purpose you can define a class that allows you to define and call methods, and determine the calling context:
var MethodsWorker = function () {
this._context = window;
this._methods = {};
}
MethodsWorker.prototype.setContext = function (context) {
this._context = context;
}
MethodsWorker.prototype.defineMethod = function (name, method) {
this._methods[name] = method;
};
MethodsWorker.prototype.invoke = function (methodName, args) {
var method = this._methods[methodName];
if (!method) { throw {}; }
return method.apply(this._context, args);
};
Usage:
var methodsWorker = new MethodsWorker ();
methodsWorker.setContext(Math);
methodsWorker.defineMethod('sqrtOfSum', function() {
var sum = 0;
for (var i = 0, n = arguments.length; i < n; i++) {
sum += arguments[i];
}
return this.sqrt(sum);
});
var result = methodsWorker.invoke('sqrtOfSum', [1, 2, 3]);
alert (result);