有什么方法可以使用纯 javascript 来执行以下操作吗?
var x = 12;
var subGlobal = {};
evalInGlobal(subGlobal, "x = 100;");
console.log(x); //--> 12
console.log(subGlobal.x); //--> 100
基本原理是我想在隔离环境中运行脚本,因此每个脚本都可以引用 x
但 x
是不同的(例如).
最佳答案
我能得到的最接近的是这个。它需要预先初始化code
中使用的global
变量集。
var evalInGlobal = function(global, code) {
global.x = null; // this is necessary
with(global) {
eval(code);
};
};
var x = 12;
var subGlobal = {};
evalInGlobal(subGlobal, "x = 100;");
console.log(x); //--> 12
console.log(subGlobal.x); //--> 100
要摆脱初始化,我认为您必须将代码块转换为可感知范围的内容。例如,将 x = 100;
翻译成 function(ctx) { ctx.x = 100; }
并通过调用 fn(global)
调用它。
这类似于 AngularJS 构建 their parser 的方式允许针对给定范围评估表达式(JS 的一个小子集)。
关于javascript - 使用不同的对象作为全局对象评估字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18771543/