嗨:)我想知道在这种情况下eval
是否安全:
!function(){
var a = 1;
!function(){
var b = 2;
try { eval.call({}, 'a'); }
catch (e) { console.log(e.message); }
try { eval.call({}, 'b'); }
catch (e) { console.log(e.message); }
}();
}();
两次调用均失败。这是否意味着 eval 无法访问周围的作用域?换句话说,使用 eval.call({}, '...')
代替 eval('...')
,可以 eval
code> 只访问对象的成员?
最佳答案
如果eval
没有“调用上下文”(基本上是this
的本地值),那么执行上下文就是全局上下文。 Section 10.4.2 of the spec.
所以这应该有效:
!function(){
var a = 1;
function evalWrapper() {
var b = 2;
try { eval('a'); console.log("yaay!"); }
catch (e) { console.log(e.message); }
};
evalWrapper.call({});
}();
规范中描述的第一个场景是:
If there is no calling context or if the eval code is not being evaluated by a direct call (15.1.2.1.1) to the eval function then,
a. Initialise the execution context as if it was a global execution context using the eval code as C as described in 10.4.1.1.
因此,除了直接调用 eval( Something )
之外,您所做的任何事情 - 包括,如果您阅读了引用的部分,则通过名称“eval”以外的其他内容引用“eval”函数! - 然后在全局上下文中评估字符串中的代码,包括全局词汇上下文。因此,就好像代码根本不在周围的函数内部。
关于javascript - 在这种情况下 eval() 是邪恶的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20974466/