Method _ Json

Source: Internet
Author: User
The simplified version implements deep Replication through Json objects. For more information, see the blog's deep replication method for Json objects.

The Code is as follows:


Var obj = {
SayName: function (){
Alert (this. name );
},
Name: 'hydrostatic yuan'
}; Var cloneObj = JSON. parse (JSON. stringify (obj); cloneObj. sayName ();


However, in this way, the attribute value cannot be copied as a function attribute. Therefore, the following code is used to improve the method:

The Code is as follows:


Var obj = {
SayName: function (){
Alert (this. name );
},
Name: 'hydrostatic yuan'
};
Function clone (){
Var str, newObj;
Str = JSON. stringify (obj, function (key, value ){
Return (typeof value = 'function '? Value. toString (). replace (/^ function (. *)/g, "jsonFunction $1"): value );
});
NewObj = JSON. parse (str, function (key, value ){
If (/^ jsonFunction (. *)/. test (value )){
Var strFun = '(' + value. replace (/^ jsonFunction (. *)/, "function $1") + ')';
Value = eval (strFun );
}
Return value;
});
Return newObj;
}
Var cloneObj = clone (obj );
CloneObj. sayName ();


Because you haven't fully tested it yet. Please be prepared!
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.