This code works as a is in the same scope where eval runs:
function compile(fn) {
//Actually calls fn.toString() then compiles some es.next type
//features to current versions of es.
return 'function () { return a; }';
}
function runAsStringA() {
var a = 10;
var compiled = eval(compile());
return compiled();
}
This doesn't work, but matches what I'd like to do in an ideal world:
function compile(fn) {
return eval('function () { return a; }');
}
function runAsStringA() {
var a = 10;
var compiled = compile();
return compiled();
}
Essentially I need a way to eval in the parent's scope.
I tried:
function compile(fn) {
return eval.bind(this, 'function () { return a; }');
}
function runAsStringA() {
var a = 10;
var compiled = compileSpecialFunction()();
return compiled();
}
The problem is that then the compiled function doesn't get a
in scope.
I'm attempting to use this in a node.js environment, so it's fine if a solution only works on node.js
It can even require some native code, although I have no experience writing native add-ons.
Unfortunately this seems to be impossible.
While I agree that you should avoid eval
, and probably veal
(as my spell checker suggests), this might help:
function compile(a) {
return eval('(function(a) { return a; })').call(this, a);;
}
function runAsStringA() {
var a = 10;
var compiled = compile(a);
return compiled;
}
console.log(runAsStringA());