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

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

问题描述

我正在寻找一种解决方案,将Javascript对象序列化(和反序列化)为跨浏览器的字符串,包括恰好是函数的对象的成员。一个典型的对象将如下所示:

  {
color:'red',
doSomething:function (arg){
alert('用'+ arg做某事');




$ doSomething()只包含局部变量(不需要也可以序列化调用上下文!)。

JSON.stringify()将忽略'doSomething'成员,因为它是一个函数。我知道toSource()方法会做我想做的事情,但它是FF特有的。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringifyrel =noreferrer> JSON.stringify 替换器类似:

  JSON.stringify {
color:'red',
doSomething:function(arg){
alert('用'+ arg做某些调用);
}
},函数(key,val){
return(typeof val ==='function')?''+ val:val;
});


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() will only contain local variables (no need to also serialize the calling context!).

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.

解决方案

You can use 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;
});

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

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