Javascript:字符串化对象(包括函数类型的成员) [英] Javascript: stringify object (including members of type function)

查看:22
本文介绍了Javascript:字符串化对象(包括函数类型的成员)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种解决方案,将 Javascript 对象序列化(和反序列化)为跨浏览器的字符串,包括恰好是函数的对象成员.一个典型的对象看起来像这样:

I'm looking for a solution to serialize (and unserialize) Javascript objects to a string across browsers, including members of the object that happen to be functions. A typical object will look like this:

{
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}

doSomething() 将只包含局部变量(不需要同时序列化调用上下文!).

doSomething() will only contain local variables (no need to also serialize the calling context!).

JSON.stringify() 将忽略 'doSomething' 成员,因为它是一个函数.我知道 toSource() 方法会做我想做的事,但它是 FF 特定的.

JSON.stringify() will ignore the 'doSomething' member because it's a function. I known the toSource() method will do what I want but it's FF specific.

推荐答案

您可以使用 JSON.stringify 带有 replacer 像:

JSON.stringify({
   color: 'red',
   doSomething: function (arg) {
        alert('Do someting called with ' + arg);
   }
}, function(key, val) {
        return (typeof val === 'function') ? '' + val : val;
});

这篇关于Javascript:字符串化对象(包括函数类型的成员)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆