在JavaScript中捕获调用者的作用域

这个代码在eval运行的同一个作用域中工作:

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(); } 

这不起作用,但匹配我想在理想世界中做的事情:

 function compile(fn) { return eval('function () { return a; }'); } function runAsStringA() { var a = 10; var compiled = compile(); return compiled(); } 

基本上我需要一种方法来评估父母的范围。

我试过了:

 function compile(fn) { return eval.bind(this, 'function () { return a; }'); } function runAsStringA() { var a = 10; var compiled = compileSpecialFunction()(); return compiled(); } 

问题是编译的函数没有得到a范围。

我试图在node.js环境中使用它,所以如果一个解决scheme只能在node.js上运行的话,那就好了

它甚至可能需要一些本地代码,尽pipe我没有经验来编写本地附加组件。

不幸的是,这似乎是不可能的。

虽然我同意你应该避免eval ,并且可能veal (正如我的拼写检查器所暗示的),但这可能有所帮助:

 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());