这篇文章提供了如何在特定上下文/范围内使用 eval 的解决方案,而无需在 eval 代码中的所有变量/函数前面加上 this
。 javascript eval in context without using this keyword
澄清一下 - 假设我有以下对象作为 eval 语句的上下文 {dog: "labrador"}
。我希望 console.log(eval(dog))
输出“labrador”,而不必输入 eval(this.dog)
但是,链接帖子中的解决方案:
function evalInContext(scr, context)
{
// execute script in private context
return (new Function( "with(this) { return " + scr + "}")).call(context);
}
使用with
语句。考虑到不鼓励使用 with
语句,是否有替代解决方案?
最佳答案
is there an alternative solution?
当然,但这比 with
更糟糕:
return new Function(...Object.keys(context), scr)(...Object.values(context));
关于Javascript - 在上下文/范围中进行评估,无需使用此关键字而不使用 with 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51698396/