首页 > Web开发 > 详细

Javascript 对象复制

时间:2014-01-14 21:37:26      阅读:505      评论:0      收藏:0      [点我收藏+]

  如果对象只是一个数据集,可采用json化再反json化的方式克隆一个对象,这个过程会丢失对象的方法。效率比较低。

  可以采用如下递归的方式复制一个对象。

bubuko.com,布布扣
function clone(target) {   
        var buf;   
        if (target instanceof Array) {   
            buf = [];  //创建一个空的数组 
            var i = target.length;   
            while (i--) {   
                buf[i] = clone(target[i]);   
            }   
            return buf;
        }else if (target instanceof Object){   
            buf = {};  //创建一个空对象 
            for (var k in target) {  //为这个对象添加新的属性 
                buf[k] = clone(target[k]);   
            }   
            return buf;   
        }else{   
            return target;   
        }   
    } 
bubuko.com,布布扣

这里注意Array的判断一定要在前面,因为数组也是一个Object(funcion也是),所以如果Object的判断在前就不会走到Array的判断了。

引申一下

bubuko.com,布布扣
var obj={};
var ary=[];
var fn=funcion(){};

alert(typeof obj) ;//object
alert(typeof ary) ;//object
alert(typeof fn) ;//function

alert(obj instanceof Object);//true
alert(ary instanceof Object);//true
alert(ary instanceof Array);//true
alert(fn instanceof Object);//true
alert(fn instanceof Function);//true
bubuko.com,布布扣

另外还找到一种方式

bubuko.com,布布扣
Object.prototype.Clone = function(){
    var objClone;
    if (this.constructor == Object){
        objClone = new this.constructor(); 
    }else{
        objClone = new this.constructor(this.valueOf()); 
    }
    for(var key in this){
        if ( objClone[key] != this[key] ){ 
            if ( typeof(this[key]) == ‘object‘ ){ 
                objClone[key] = this[key].Clone();
            }else{
                objClone[key] = this[key];
            }
        }
    }
    objClone.toString = this.toString;
    objClone.valueOf = this.valueOf;
    return objClone; 
} 
bubuko.com,布布扣

Javascript 对象复制

原文:http://www.cnblogs.com/onlywujun/p/3513551.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!