码迷,mamicode.com
首页 > Web开发 > 详细

JS对象转字符串保留方法,字符串转对象

时间:2016-05-16 17:06:18      阅读:328      评论:0      收藏:0      [点我收藏+]

标签:

var obj = {
            name:"zhangsan",
            age:20,
            say:function(name){
                console.log("My name is " + (name ? name : this.name));
            },
            hello:function(){
                console.log("Hello");
            },
            talk:function(name, age){
                console.log("My name is " + (name ? name : this.name) + ",my age is " + (age ? age : this.age));
            }
    };

    function stringifyObj(obj){
        var newObj = {};
        for(var key in obj){
            if(obj.hasOwnProperty(key) && obj[key] instanceof Function){
                newObj[key] = obj[key].toString().replace(/[\n\t]/g,"");
                continue;
            }
            newObj[key] = obj[key];
        }
        return JSON.stringify(newObj);
    }


    function parseObj(strObj){
        var obj = JSON.parse(strObj);
        var funReg = /function\s\(.*\)/;
        for(var key in obj){
            if(funReg.test(obj[key])){
                try{
                    var fun = (new Function("return " + obj[key]))();
                    if(fun instanceof Function){
                        obj[key] = fun;
                    }
                }catch(e){
                    console.log(e)
                }
            }
        }
        return obj;
    }

 

JS对象转字符串保留方法,字符串转对象

标签:

原文地址:http://www.cnblogs.com/lweiruil/p/5498245.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!