The author's hair is a picture, we can enlarge to see.
A few days ago said about JavaScript literal syntax problem, feel very interesting, and then studied, can the object again into literal form? Just like we usually say about serialization and deserialization. Of course, because the JavaScript object itself provides a ToString () method, by default it returns the literal form of a simple object.
What we need to do is to judge the specific type of object, then serialize each object separately, then output as Object literal syntax form. To accurately judge the type of object, use the __typeof__ method I once said, the code for serializing an instance of an object is as follows:
Copy Code code as follows:
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;
}
}
};
In fact, the array and object properties compared to the trouble, you need to do this serialize operation recursively. However, it is necessary to note that the Serialize method does not need to be serialized. The following is a test example, but the serialization method does not check the ring reference and the objects that can be serialized are limited.
Copy Code code as follows:
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 ());
As for deserialization, it's very easy to get a class instance by executing the serialization result with Eval.