hermann
hermann

Reputation: 6295

Executing JS string parameters as methods

I have to build a function that will execute some tasks.

The tasks will be a parameter of the function, most likely a string array. It might look something like this :

['refresh', 'close', 'show']

The strings correspond to actual methods.

Is it possible to somehow execute the methods by using the strings of the array?

Upvotes: 0

Views: 31

Answers (2)

gustavohenke
gustavohenke

Reputation: 41440

Short answer:

Yup:

var method = "refresh";
yourObject[method]();

Long answer:

It's possible, but your methods must be namespaced. The following example will work, if you're in a browser context, because every global function is a property of window:

function refresh() {
    // do it
}
var method = "refresh";
window[method]();

// or maybe
var yourObject = { refresh: function() { ... } };
yourObject[method]();

However, the following won't work (I'm showing it because closures are a common pattern in javascript):

(function() {
   function refresh() {
       // do it
   }

   var method = "refresh";
   // which object contains refresh...? None!
   // yourObject[method]();
})();

Upvotes: 2

Stefano Ortisi
Stefano Ortisi

Reputation: 5326

if your methods are attached to the window object then you can do something like this:

var methods = [ 'refresh', 'close', 'show' ];
for( var i in methods ) {
    funk = window[ methods[ i ] ];
    if( typeof funk === 'function') {
        window.funk();
    }
}

Otherwise, if your methods are methods of another object you can easily replace window with your object.

Upvotes: 1

Related Questions