对象合并_拷贝

	function merae(obj1, obj2) {
		
	    for (var p in obj2) {
		   try {
		 
			 if ( obj2[p].constructor==Object ) {
				obj1[p] = merae(obj1[p], obj2[p]);
			 } else {
				obj1[p] = obj2[p];
			 }
		
		   } catch(e) {
			 //未设置目标对象中的属性;创建它并设置其值。
			 obj1[p] = obj2[p];
		   }
	    }
	
			
		var o1={
			a:1,
			b:{bb:2},
			c:{cc:3,ccc:4}
		};
		var o2={d:9,a:2};

		merae(o2,o1);
		//console.log(o2);//{a: 1,b: {bb: 2},c: {cc: 3, ccc: 4},d: 9}
		o1.a=5;
		//深拷贝不是浅拷贝
		//console.log(o2);//{a: 1,b: {bb: 2},c: {cc: 3, ccc: 4},d: 9}
		//console.log(o1);//{a:1,b:{bb:2},c:{cc:3,ccc:4}};
	function deepClone(source){
		let targetObj = source.constructor === Array ? [] : {}; 
			for(let keys in source){
				if(source.hasOwnProperty(keys)){
					if(source[keys] && typeof source[keys] === 'object'){
						
						targetObj[keys] = source[keys].constructor === Array ? [] : {};
						targetObj[keys] = deepClone(source[keys]);
						
					}else{
						
						targetObj[keys] = source[keys];
					}
				}
			}
		return targetObj;
	}
	
	
	var o1={
		a:1,
		b:{bb:2},
		c:{cc:3,ccc:4}
	};
	
	let o2=deepClone(o1);
	console.log(o2);
	o1.a=5;
	console.log(o2);//{a: 1, b: {…}, c: {…}}
	console.log(o1);//{a: 5, b: {…}, c: {…}}
上一篇:this指向


下一篇:实体类之间属性对比的方法