For example, if I have this:
var foo = 444;
var x = new Function("console.log('5'); console.log(foo);");
x();
It says foo is undefined. I want to be able to access foo and many other global variables within this new Function
context.
One solution is:
var foo = 444;
var x = new Function('foo', "console.log('5'); console.log(foo);");
x(foo);
But this requires passing everything through as separate parameters. Too cumbersome.
The only alternative I can think of is have a container object hold every single variable and then only pass that container:
var container = { };
container.foo = 444;
var x = new Function('container', "console.log('5'); console.log(container.foo);");
x(container);
But that requires having to put every one of my variables in to the container.
I can't do something like this:
var x = new Function('container', "console.log('5'); console.log(" + foo + ");");
because I need to evaluate foo
at the time of the function exeuction. Not when x
is declared.
I know using new Function
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.