Home > Web Front-end > JS Tutorial > body text

Summary of three methods for cloning javascript objects_javascript skills

WBOY
Release: 2016-05-16 18:12:06
Original
940 people have browsed it

Method 1

Copy code The 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 code The 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 code The 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 labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!