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

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

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;   
        }   
    } 

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

引申一下

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

另外还找到一种方式

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; 
} 

 

 

相关文章:

  • 2022-12-23
  • 2022-02-19
  • 2022-01-09
  • 2022-12-23
  • 2021-06-16
  • 2021-12-25
  • 2021-12-22
  • 2022-02-16
猜你喜欢
  • 2017-12-12
  • 2021-10-08
  • 2021-05-30
  • 2021-11-10
相关资源
相似解决方案