This link shows you that jQuery uses (new Function("return " + data))(); for older browsers, to parse a JSON string instead of eval().
What are the benefits of this? What if the JSON string isn’t safe?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
The quote in Nick’s answer hints at it. It’s not really a big difference, but the feeling is that
evalis ‘worse’ thannew 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.Specifically:
gives
2. Theevaled string has operated onvictim‘s local variable scope! This is something that a regular user-written function could never do;evalcan only do it because it is dark magic.Using a regular function instead takes away this element of magic:
in the above, the returned
aremains1; the new Function can only operate on its own local variables or the globalwindow.a.That knowledge allows code analysis tools — which might include JavaScript engines and particularly clever minifiers — to apply more optimisations. For example the second
victimfunction could have theavariable completely optimised away toreturn 1. One use ofevaland a lot of potential optimisations aren’t going to be doable.Of course in practice for a tiny function like a JSON
evaler, there isn’t going to be a noticeable difference, but in general the thinking is:new Functionis preferable toeval, unless you really need the code to access the calling function’s local variables.