可能有一些关闭编译选项,允许这种特别的事情,但做不到这一点,我会解决这个问题的两种方法之一:
选项1
创建一个全局对象来存储您的变量,然后使用js_externs
选项,以防止它被改写的:
// ==ClosureCompiler==
// @compilation_level ADVANCED_OPTIMIZATIONS
// @output_file_name default.js
// @js_externs vars
// ==/ClosureCompiler==
vars = {};
那么你可以申请字符串属性到这个对象应该保持不变
function scopedEval(code){
vars['some_var'] = 'world';
return eval('('+code+')');
}
scopedEval('alert("hello, "+vars["some_var"])');
选项2
如果由于某种原因vars['some_var']
不会为你工作,你需要使用some_var
字面上eval
版代码中,然后就可以用with
来解决这个问题。在这种情况下,您不需要声明vars
作为extern。
function scopedEval(code){
var vars = {
"some_var": "world"
};
with(vars) {
return eval('('+code+')');
}
}
scopedEval('alert("hello, "+some_var)');
我把它留给你的判断力,你是否觉得脏使用JavaScript的两个功能,吸引了最多的一起矾,即with
和eval
。
用'with'声明没问题。你只需要知道如何安全地使用它。不过,我会继续寻找一种不改变代码的方式。 – GetFree
另一种选择是使用函数构造函数: new Function(“code”,“return eval('('+ code +')');”); – John