前些天说过关于JavaScript的Literal Syntax问题,觉得挺有意思的,于是又研究了一下,能不能把对象再转化为Literal形式呢?就像我们平时说的序列化和反序列化啥的。当然可以了,因为JavaScript对象自身都提供了一个toString()方法,默认就是返回简单对象的Literal形式。
我们需要作的就是判断对象的具体类型,然后分别Serialize每种对象,再输出为Object的Literal语法形式就行了。准确的判断对象类型,使用我曾经说过的__typeof__方法就行了,序列化对象实例的代码如下:
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执行一下,就得到类实例了。
本文转自博客园鸟食轩的博客,原文链接:http://www.cnblogs.com/birdshome/,如需转载请自行联系原博主。