开发者

Trouble understanding jQuery.parseJSON JSON.parse fallback

开发者 https://www.devze.com 2023-03-27 07:02 出处:网络
This is the source of $.parseJSON function (data) { if (typeof data !== \"string\" || !data) { return null;

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

  1. How this parsin开发者_如何学编程g fallback works really?
  2. 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号