0

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?

asked Feb 17, 2014 at 17:06

2 Answers 2

2

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]();
})();
answered Feb 17, 2014 at 17:10
Sign up to request clarification or add additional context in comments.

Comments

1

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.

answered Feb 17, 2014 at 17:11

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.