1

I would like to call a function within a function from a string variable with arguments.

Let me demonstrate what I would like with adding some code

var myFunction = function() {
    var innerFunction = function(data) {
        alert(data);
    }

    return {
        run: function(data) {
            innerFunction(data);
        }
    }
};

var myString = "myFunction.run()";

If I don't want to pass variable than it is quite easy;

var callFunction = new Function(myString);
callFunction();

If I can pass a variable without using function within a function;

function myFunction(data) {
    alert(data);
}

var myString = "myFunction";
window[myString]("Hello World!");

However this is not what I want. Could anyone enlighten me about calling a function within a function from a string variable with passing arguments to it?

Revenant
  • 2,942
  • 7
  • 30
  • 52

2 Answers2

0

It might be helpful

var myfun = function(){
 console.log('Hello');
}

window['myfun']();

Output: Hello

Ramesh Murugesan
  • 4,727
  • 7
  • 42
  • 67
0

Well, it seems posting on SOF helps me to think better.

I forgot to try this one;

var functionName = myString.split('.');
window[functionName[0]][functionName[1]]("Hello World");

It works as expected. Thank you everyone.

Revenant
  • 2,942
  • 7
  • 30
  • 52