javascript里面对象的等号赋值操作是引用方式,如果想要使用拷贝赋值操作需要实现像java中clone一样的功能,实现方法就是逐项拷贝对象的内容。实现如下:
方法一:
function clone(myObj){ if(typeof(myObj) != 'object') return myObj; if(myObj == null) return myObj; var myNewObj = new Object(); for(var i in myObj) myNewObj[i] = clone(myObj[i]); return myNewObj; }
方法二:通过object原型扩展实现
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; }