您的位置:首页 > Web前端 > JavaScript

Js深度克隆对象(对象的属性含有对象数组)

2013-06-16 19:18 447 查看
这个方法当时在做项目时写的,应用在easyui的Tree组件中。

后台Java对象结构:List<TreeObj>

public class TreeObj {
	private String id;
	private String text;
	private List<TreeObj> children = new ArrayList<TreeObj>();
	private String state ;
	private String iconCls;
	private Object attributes ;
	private boolean checked = false;
}


js代码:

//克隆树数据对象
function clone(targetList,childrenList,cloneList){
	for(key in targetList){
		//----取值  start--------------------------------------------------------
		var obj = targetList[key];
		var newObj = {};
		newObj.id = obj.id;
		newObj.text = obj.text;
		newObj.state =obj.state;
		newObj.checked = obj.checked;
		var attr = {};attr.parentNode ="";attr.nodeHeirdomRelation = "";
		if(obj.attributes){
			if(obj.attributes.parentNode){
				attr.parentNode = obj.attributes.parentNode ;
			}
			if(obj.attributes.nodeHeirdomRelation){
				attr.nodeHeirdomRelation = obj.attributes.nodeHeirdomRelation ;
			}
		}
		newObj.attributes = attr;
		//---取值  end---------------------------------------------------------
		if(childrenList){childrenList.push(newObj);}//保存子节点成员
		
		if(obj.children != null && obj.children.length>0){	
			var newList = new Array();//保存当前节点的子节点		
			clone(obj.children,newList,cloneList);			
			newObj.children = newList;			
		}
		if(/^rl_.*$/.test(obj.id.toLowerCase())){//从根部开始保存
			cloneList.push(newObj);//保存根节点
		}
	}
}


调用;

clone(源数组,null,克隆后);



在网上找到这个办法,但好像不能克隆带对象属性的数组,目前我还没对他进行过测试。

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; 
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: