时间:2021-07-01 10:21:17 帮助过:4人阅读
Object.prototype.Serialize = function()
{
var type = __typeof__(this);
switch(type)
{
case 'Array' :
{
var strArray = '[';
for ( var i=0 ; i < this.length ; ++i )
{
var value = '';
if ( this[i] )
{
value = this[i].Serialize();
}
strArray += value + ',';
}
if ( strArray.charAt(strArray.length-1) == ',' )
{
strArray = strArray.substr(0, strArray.length-1);
}
strArray += ']';
return strArray;
}
case 'Date' :
{
return 'new Date(' + this.getTime() + ')';
}
case 'Boolean' :
case 'Function' :
case 'Number' :
case 'String' :
{
return this.toString();
}
default :
{
var serialize = '{';
for ( var key in this )
{
if ( key == 'Serialize' ) continue;
var subserialize = 'null';
if ( this[key] != undefined )
{
subserialize = this[key].Serialize();
}
serialize += '\r\n' + key + ' : ' + subserialize + ',';
}
if ( serialize.charAt(serialize.length-1) == ',' )
{
serialize = serialize.substr(0, serialize.length-1);
}
serialize += '\r\n}';
return serialize;
}
}
};
其实就是Array和Object的属性比较的麻烦,需要递归的做这个Serialize操作。不过需要注意,Serialize方法就不需要被序列化出来了。下面是测试示例,不过这个序列化方法没有对环状引用做检查,能序列化的对象很有限。
代码如下:
var obj1 = [];
alert(obj1.Serialize());
var obj2 = [1,[2,[3,[4,[5,[6,[7,[8,[9,[0]]]]]]]]]];
alert(obj2.Serialize());
var obj3 =
{
Properties1 : 1, Properties2 : '2', Properties3 : [3],
Method1 : function(){ return this.Properties1 + this.Properties3[0];},
Method2 : function(){ return this.Preperties2; }
};
alert(obj3.Serialize());
var obj4 = [null, 1, 'string', true, function(){return 'keke';}, new Object()];
alert(obj4.Serialize());
至于反序列化就非常的容易了,把上面的序列化结果用eval执行一下,就得到类实例了。