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; }
时间: 2024-10-09 10:24:01