0

I am trying to call a function using a variable with it's name.

Here's the code:

var selectedFunc = 'func2';

var myModule = {

    func1: function() {
       //something here  
    },

    func1: function() {
       //something here 
    }

};

myModule.selectedFunc();

I would normally do this:

myModule.func1();

which will work but I'm trying to use the variable to define it's name, which is not working.

How can I fix this issue?

Satch3000
  • 47,356
  • 86
  • 216
  • 346

3 Answers3

5

You can use bracket notation:

myModule[selectedFunc]();
tymeJV
  • 103,943
  • 14
  • 161
  • 157
0

Use eval.

var selectedFunc = 'func2';

var myModule = {

    func1: function() {
       return "hello";
    },

    func2: function() {
       return "world"; 
    }

};

window.alert(eval("myModule." + selectedFunc + "()"));
Samuel Toh
  • 18,006
  • 3
  • 24
  • 39
0

You could call it using the following syntax

setTimeout("myModule."+selectedFunc + "()", 0);

Or even using eval to call it

eval("myModule." + selectedFunc).call();
Muhammad Soliman
  • 21,644
  • 6
  • 109
  • 75