Summary of three methods for cloning javascript objects

Source: Internet
Author: User

Method 1
Copy codeThe Code is as follows:
Function clone (obj ){
Var o;
Switch (typeof obj ){
Case 'undefined': break;
Case 'string': o = obj + ''; break;
Case 'number': o = obj-0; break;
Case 'boolean': o = obj; break;
Case 'object ':
If (obj = null ){
O = null;
} Else {
If (obj instanceof Array ){
O = [];
For (var I = 0, len = obj. length; I <len; I ++ ){
O. push (clone (obj [I]);
}
} Else {
O = {};
For (var k in obj ){
O [k] = clone (obj [k]);
}
}
}
Break;
Default:
O = obj; break;
}
Return o;
}

Method 2
Copy codeThe Code is as follows:
Function clone2 (obj ){
Var o, obj;
If (obj. constructor = Object ){
O = new obj. constructor ();
} Else {
O = new obj. constructor (obj. valueOf ());
}
For (var key in obj ){
If (o [key]! = Obj [key]) {
If (typeof (obj [key]) = 'object '){
O [key] = clone2 (obj [key]);
} Else {
O [key] = obj [key];
}
}
}
O. toString = obj. toString;
O. valueOf = obj. valueOf;
Return o;
}

Method 3
Copy codeThe Code is as follows:
Function clone3 (obj ){
Function Clone (){}
Clone. prototype = obj;
Var o = new Clone ();
For (var a in o ){
If (typeof o [a] = "object "){
O [a] = clone3 (o [a]);
}
}
Return o;
}

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.