How to access global variables within a new Function context?
<p>For example, if I have this:</p>

<pre><code>var foo = 444;

var x = new Function("console.log('5'); console.log(foo);");

x();
</code></pre>

<p>It says foo is undefined. I want to be able to access foo and many other global variables within this <code>new Function</code> context.</p>

<p>One solution is:</p>

<pre><code>var foo = 444;

var x = new Function('foo', "console.log('5'); console.log(foo);");

x(foo);
</code></pre>

<p>But this requires passing everything through as separate parameters. Too cumbersome.</p>

<p>The only alternative I can think of is have a container object hold every single variable and then only pass that container:</p>

<pre><code>var container = { };

container.foo = 444;

var x = new Function('container', "console.log('5'); console.log(container.foo);");

x(container);
</code></pre>

<p>But that requires having to put every one of my variables in to the container.</p>

<p>I can't do something like this:</p>

<pre><code>var x = new Function('container', "console.log('5'); console.log(" + foo + ");");
</code></pre>

<p>because I need to evaluate <code>foo</code> at the time of the function exeuction. Not when <code>x</code> is declared.</p>

<p>I know using <code>new Function</code> uses eval and it's generally evil. I'm writing a code parser and I'm trying to optimize it so I'm using it anyway.</p>