如果您想接受甚至是远程复杂的脚本,这将不起作用。几个潜在的问题:
范围
var i = 1; // global scope
!function() {
var i = 2; // function scope
}();
alert(i); // 1
对比
myEval('var i = 1;'); // global scope
myEval('!function() {
myEval(\'var i = 2;\'); // eval has global scope, always
}();');
myEval('alert(i);'); // 2
闭包
!function() {
var i = 1; // local to outer function
!function() { // inherits context from outer function
alert(i); // 1
}();
}();
对比
myEval('!function() {
myEval(\'var i = 1;\'); // local to outer function
myEval(\'!function() { // eval has global scope; myEval inherits from wherever it was defined
myEval(\\\'alert(i);\\\'); // undefined
}();\');
}();');
这个
var obj = {
n: 1,
f: function() {
return this.n; // this is the object f is called from
}
}
alert(obj.f()); // 1
对比
myEval('var obj = {
n: myEval(\'1\'),
f: myEval(\'function() {
return myEval(\\\'this.n\\\'); // this is always the window in eval
}')
}');
myEval('alert(obj.f());'); // undefined
逃脱蠕变
你需要转义每一个引用,你也需要转义转义符号。在包含大量对象、闭包、内部函数等的代码中,这将导致转义符号变得难以管理:
!function() {
$(function() {
$('#foo').click(function() {
setTimeout(function() {
$.post('/', function(res) {
log(res);
});
}, 1000);
});
});
}();
(请注意,这不是一个特别人为或复杂的示例,它仅涉及在某个事件上触发回调的延迟动作)
myEval('!function() {
myEval(\'$(myEval(\\\'function() {
myEval(\\\\\\\'$(\\\\\\\'#foo\\\\\\\').click(myEval(\\\\\\\\\\\\\\\'function() {
myEval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'setTimeout(myEval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'function() {
myEval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\'$.post('/', myEval(\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\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