编辑代码

// 简单的沙盒示例
// 在一些需要创建隔离执行环境的场景中,可以使用 new Function() 来实现简单的沙盒。通过严格控制传入的参数和函数体,可以限制代码的执行范围。
const sandbox = (code, context) => {
    const keys = Object.keys(context);
    const values = Object.values(context);
    const func = new Function(...keys, `with(this) { return ${code}; }`);
    // 通过function.apply来改变this指向
    return func.apply(context, values);
};

const context = { x: 5, y: 10 };
const result = sandbox('x + y + c', context);
console.log(result); // 输出: 15