是否存在一个字符串,s这样
(new Function(s))();
Run Code Online (Sandbox Code Playgroud)
和
eval(s);
Run Code Online (Sandbox Code Playgroud)
表现不同?我正试图"检测"字符串的评估方式.
Som*_*Guy 31
检查arguments对象.如果它存在,那么你就在这个功能中.如果没有,它已被eval编辑.
请注意,您必须将检查放在如下arguments的try...catch块中:
var s = 'try {document.writeln(arguments ? "Function" : "Eval") } catch(e) { document.writeln("Eval!") }';
(new Function(s))();
eval(s);
Run Code Online (Sandbox Code Playgroud)
解决方案nnnnnn的问题.为此,我编辑了eval函数本身:
var _eval = eval;
eval = function (){
// Your custom code here, for when it's eval
_eval.apply(this, arguments);
};
function test(x){
eval("try{ alert(arguments[0]) } catch(e){ alert('Eval detected!'); }");
}
test("In eval, but it wasn't detected");?
Run Code Online (Sandbox Code Playgroud)
Ben*_*aum 14
由于您无法重新定义eval,因此当前答案在严格模式下不起作用.此外,eval由于许多其他原因,重新定义是有问题的.
区分它们的方法是基于这样一个事实......其中一个创建了一个函数而另一个函数没有.功能有什么作用?他们可以return东西:)
我们可以简单地利用它并做一些事情return:
// is in function
try {
return true;
} catch(e) { // in JS you can catch syntax errors
false; //eval returns the return of the expression.
}
Run Code Online (Sandbox Code Playgroud)
所以在例子中:
var s = "try{ return true; }catch(e){ false; }";
eval(s); // false
Function(s)(); // true
(new Function(s))(); // true, same as line above
(function(){ return eval(s); })(); // the nested 'problematic' case - false
Run Code Online (Sandbox Code Playgroud)