我有以下javaScript"class":
A = (function() {
a = function() { eval(...) };
A.prototype.b = function(arg1, arg2) { /* do something... */};
})();
Run Code Online (Sandbox Code Playgroud)
现在让我们假设在eval()中我传递的字符串包含调用带有一些参数的表达式:
b("foo", "bar")
Run Code Online (Sandbox Code Playgroud)
但后来我得到b没有定义的错误.所以我的问题是:如何在A类语境中调用eval?
有什么办法可以在特定范围内执行eval()(但不是全局)?
例如,以下代码不起作用(在第二个语句中未定义)因为它们位于不同的范围内:
eval(var a = 1);
eval(alert(a));
Run Code Online (Sandbox Code Playgroud)
如果可能的话,我想动态创建一个范围.例如(语法肯定是错误的,但只是为了说明这个想法)
var scope1;
var scope2;
with scope1{
eval(var a = 1); eval(alert(a)); // this will alert 1
}
with scope2{
eval(var a = 1); eval(a++); eval(alert(a)); // this will alert 2
}
with scope1{
eval(a += 2); eval(alert(a)); // this will alert 3 because a is already defined in scope1
}
Run Code Online (Sandbox Code Playgroud)
有关如何实现这样的事情的任何想法?谢谢!