Three ways to clone a JavaScript object summary _javascript tips

Source: Internet
Author: User
Method One
Copy Code code as follows:

function Clone (obj) {
var o;
Switch (typeof obj) {
Case ' undefined ': break;
Case ' string ': o = obj + ';
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 Two
Copy Code code 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 Three
Copy Code code 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.