Javascript:stringify对象(包括类型函数的成员) [英] Javascript: stringify object (including members of type function)
问题描述
我正在寻找一种解决方案,将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屋!