3

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.

3 Answers 3

8

If 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]();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much. Working fine.
6

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)();

Comments

1

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.