Using a variable as a function call

Hello,

I was wondering how can I call a function by using the value of a variable name?

i.e.


var str = "function_name";
// call 'function_name' by using its 'str' alias

Thanks.

You will need to assign the function to a named property of an object. For example


var somObj = {};
function foo(){}
someObj.foo = foo;
someObj.bar = function(){}

//then 
someObj[str](arg1, arg2 ...)

Also, if the function was declared in the global scope, it’s automatically a property of the window object. So you can do windowstr

If these aren’t possible, then you need to use eval(). Try hard not to use it.

Thanks for that :slight_smile:

Thanks for the tips. I was searching for info about how to do this a month or two ago and found very little information. I did find out how to do it using the window object as you mentioned.

As for your code, would it be something like this?:
//then
someObj[foo](arg1, arg2 …)

The someObj[str](arg1, arg2 …) throws me because I don’t know where the str comes from.

I am nothing more than a beginner at Javascript. Bear with me. :slight_smile:

With that example the value of str would be either ‘foo’ or ‘bar’ depending on which of the two functions you are running.

Thanks for that, Felgall, I had the same question as cheesedude.

…and to make sure I “got it” right, we are using the [bracket] notation instead of .dot notation in order to list the args?

Well, using brackets to access the property. The value of the property in our case happens to be a function.


var someObj = {};
someObj.hi = function(name) {
    alert("hi, " + name);
}
someObj.bye = function(name) {
    alert("bye, " + name);
}

var str = "hi";
someObj[str]("Stomme poes");
var str = "bye";
someObj[str]("Stomme poes");

//you can even
var str = "hi";
var theFunction = someObj[str];
theFunction("Stomme poes");

Thanks for the clarification, crmalibu. This is interesting to know. And it is very hard to find on the internet. I don’t know why this info is so hard to find. But it is.

Now we know. :slight_smile: