(New Function ("return" + JSON)) ();

Source: Internet
Author: User
Tags string to json

2015-9-15 16:26:05

I've seen this code these days:

var tojson=function(A) {                            try                {            ////run return in the body (return a); return a.             return (new Function ("return" + A        )) (); Catch (e)        {            return "";        }    };

I don't know what that means. Asked a colleague later said that the string into JSON, or do not understand what the principle is. So Baidu, saw such a question and answer: (New Function ("return" + str)); Solve why it is wide to convert a JSON string to JSON. The JS master know the reason, pointing out, got a day did not understand why.

Answer: The new function () receives the string and converts it into a function. When converting "return" + str into a function, Str is converted to an object (not converted to JSON) and then used (function () {return obj;}) () method immediately executes the function generated by the new function (), which has only one return obj, and the result is the object that the STR string is converted from.

(New Function ("return" + JSON)) ();

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.