[英]Trouble understanding jQuery.parseJSON JSON.parse fallback
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 + ')')
我想知道這些事情
new Function()
更快) new Function()
允許您將函數作為字符串傳遞。
在這種情況下,創建函數以簡單地返回由json字符串描述的對象。 由於json是有效的對象文字,因此該函數只返回json中定義的對象。 立即調用新函數,返回該對象。
就性能而言,一些快速的谷歌搜索發現聲稱new Function()
比eval
更快,盡管我自己沒有測試過。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.