Search code examples
javascripteval

Using JavaScript's eval() with multiple dependent functions


How do I load dynamic dependencies into an eval() call? (If at all possible)

I am trying to run a call to eval() using multiple functions but I can't seem to get it to work. ie:

function foo() {
    return bar;
}

function foo2() {
    return foo();
}

Ideally, what I want to work is:

eval("
    (function() { 
        function foo() {
            return bar;
        }

        return foo(); 
     }())
");

But I keep getting an error that foo is not defined.

I know that if foo() is defined in the html of my page, then I can use eval() to write a function that is basically foo2() and get the result I want:

eval("
    (function() { 
        return foo(); 
     }())
");

But I want to be able to change both functions and still be able to call foo2() which will always reference foo(). Is this possible? What are some ways I could get this working?


Solution

  • Try and type this into the textarea:

    function hello(name) {
      alert("hello" + name);
    }
    

    Then func will be a reference to hello (func == hello). Then you can use func to test the testcases like it was hello for example.

    var ta = document.getElementById("code");
    
    function run() {
      var code = "(function() { return " + ta.value + "; })()"; // code that will return a reference to the function typed by the user
      
      var func = eval(code); // func will be the function the user typed in the textarea
      
      func("me"); // you can call it like you want
    }
    <textarea id="code"></textarea>
    <button onclick="run()">Run</button>