Trouble understanding jQuery.parseJSON JSON.parse fallback
This is the source of $.parseJSON
function (data) {
if (typeof data !== "string" || !data) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim(data);
// Attempt to parse using the native JSON parser first
if (window.JSON && window.JSON.parse) {
return window.JSON.parse(data);
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if (rvalidchars.test(data.replace(rvalidescape, "@").replace(rvalidtokens, "]").replace(rvalidbraces, ""))) {
return (new Function("return " + data))();
}
jQuery.error("Invalid JSON: " + data);
}
I have trouble understanding the following fallbacks
return (new Function("return " + data))();
and also ( this one is not in jQuery )
return (eval('('+ data + ')')
I would like to know these things
- How this parsin开发者_如何学编程g fallback works really?
- Why eval is not used in the fallback? (Is it not faster than
new Function()
)
new Function()
allows you to pass your function as a string.
In this case, the function is created to simply return the object described by the json string. Since the json is a valid object literal, this function simply returns the object defined in the json. The new function is immediately invoked, returning that object.
As far as performance, some quick googling found claims that new Function()
is faster than eval
, though I have not tested this myself.
精彩评论