如果對象只是一個數據集,可采用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; }