簡體   English   中英

無法理解jQuery.parseJSON JSON.parse后備

[英]Trouble understanding jQuery.parseJSON JSON.parse fallback

這是$.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);
}

我無法理解以下后備

return (new Function("return " + data))();

而且(這個不是在jQuery中)

return (eval('('+ data + ')')

我想知道這些事情

  1. 這個解析后備如何工作呢?
  2. 為什么eval不用於后備? (它不比new Function()更快)

new Function()允許您將函數作為字符串傳遞。

在這種情況下,創建函數以簡單地返回由json字符串描述的對象。 由於json是有效的對象文字,因此該函數只返回json中定義的對象。 立即調用新函數,返回該對象。

就性能而言,一些快速的谷歌搜索發現聲稱new Function()eval更快,盡管我自己沒有測試過。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM