當瀏覽器不支援JSON.parse(), 用new Function解決, 而非eval()

為何選擇用new Function?

jQuery uses (new Function(“return ” + data))(); instead of eval(data); to parse JSON, why?
http://stackoverflow.com/questions/2449220/jquery-uses-new-functionreturn-data-instead-of-evaldata-to-parse

擷取答案重點如下:

the feeling is that eval is ‘worse’ than new Function.
--> Not in terms of security — they're both equally useless in the face of untrusted input, but then hopefully your webapp is not returning untrusted JSON strings — 
--> but in terms of language-level weirdness, and hence resistance to optimisation.

e.g.

function victim() {

    var a= 1;
    eval('a= 2');
    return a;                                  // 2 --> something that a regular user-written function could never do; eval can only do it because it is dark magic.

}


Using a regular function instead takes away this element of magic:

function victim() {

    var a= 1;
    (new Function('a= 2;'))();
    return a;                                  // 1

}

in the above, the returned a remains 1; the new Function can only operate on its own local variables or the global window.a.


in general the thinking is:

-> avoid both approaches wherever possible (they are both disallowed in ECMAScript Fifth Edition's Strict Mode);

--> if you have to use one, new Function is preferable to eval, unless you really need the code to access the calling function's local variables.



留言

熱門文章