js str转json、有段代码看不懂、请教授翻译

先谢谢了

    var str = '{"a":"a","b":"b"}';
    var jsonstr;
    ~(function strToJson(str){
        jsonstr = (new Function("return " + str))();
//        return jsonstr;
    })(str);

    console.log(typeof jsonstr);                    //object
    console.log(jsonstr);                           //Object {a: "a", b: "b"}
阅读 2.1k
2 个回答

看看MDN上new function的例子

// 创建了一个能返回两个参数和的函数
const adder = new Function("a", "b", "return a + b");

// 调用函数
adder(2, 6);
//  8

new Function ([arg1[, arg2[, ...argN]],] functionBody)

在本例子中
jsonstr = (new Function("return " + str))();
即为:
jsonstr = (new Function("return {'a':'a','b':'b'}"))();
动态编译了functionBody,实际效果是:
jsonstr = (function(){return {"a":"a","b":"b"}})();

是哪里看不懂呢?我注释了下,截图如下:
图片描述

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题