我正在寻找一种解决方案来跨浏览器将 Javascript 对象序列化(和反序列化)为字符串,包括恰好是函数的对象成员。一个典型的对象看起来像这样:
{
color: 'red',
doSomething: function (arg) {
alert('Do someting called with ' + arg);
}
}
doSomething() 将仅包含局部变量(无需序列化调用上下文!)。
JSON.stringify() 将忽略 'doSomething' 成员,因为它是一个函数。我知道 toSource() 方法会执行我想要的操作,但它是 FF 特定的。
您可以使用JSON.stringify https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify with a replacer
like:
JSON.stringify({
color: 'red',
doSomething: function (arg) {
alert('Do someting called with ' + arg);
}
}, function(key, val) {
return (typeof val === 'function') ? '' + val : val;
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)