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?

4
  • 1
    This would still help you stackoverflow.com/a/359910/2466168 Commented Apr 6, 2015 at 12:22
  • 2
    If you found solution by yourself then please post it as an answer and accept it. Commented Apr 6, 2015 at 12:24
  • Visit stackoverflow.com/questions/29162944/… Commented Apr 6, 2015 at 12:56
  • @phts I tried but it warned me to add it as a comment so I ended up editing my question Commented Apr 6, 2015 at 13:09

2 Answers 2

0

It might be helpful

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

window['myfun']();

Output: Hello

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

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.