JavaScript Fix Eval Return Error ?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<script language="javascript" type="text/javascript">
function testEval() {
var code = "";

// 在 eval 方法中,遇到 Return 時,會有 Error ?
/*
* code = "if (10 === 10) { alert('Yes'); return true; } else { alert('No'); return false; }";
* eval(code);
*/


// 解決方法?
code += "new function() {";
code += " if (10 === 10) {";
code += " this.result = true;";
code += " }else{";
code += " this.result = false;";
code += " }";
code += " return this.result;";
code += "}";

alert(eval(code).result ? 'Yes' : 'No');
}

testEval();
</script>