浅复制,如果属性是对象或者数组的时候,可能会导致以外
function extend(parent, child) { var i; child = child || {}; for (i in parent) { if (parent.hasOwnProperty(i)) { child[i] = parent[i]; } } return child; } var dad = {name:"jie"}; var kid = extend(dad); console.log(kid.name); //jie var dad ={ counts:[1,2,3], reads:{paper:true} } var kid = extend(dad); //处理数组和对象的之后,这种浅复制可能导致意外发生 kid.counts.push(4); kid.reads.paper = false; console.log(dad.counts); //[ 1, 2, 3, 4 ] console.log(dad.reads); //{ paper: false }
深度复制,解决复制对象或者数组出现的问题。
//深度复制实现,利用了递归方法 function extendDeep(parent, child) { var i, toStr = Object.prototype.toString, astr = "[object Array]"; child = child || {}; for (i in parent) { if (parent.hasOwnProperty(i)) { if (typeof parent[i] === "object") { child[i] = (toStr.call(parent[i] === astr)) ? [] : {}; extendDeep(parent[i], child[i]); } else { child[i] = parent[i]; } } } return child; } var dad = { counts: [1, 2, 3], reads: {paper: true} }; var kid = extendDeep(dad); kid.counts.push(4); console.log(kid.counts); //[ 1, 2, 3, 4 ] console.log(dad.counts); //[ 1, 2, 3 ] console.log(dad.reads === kid.reads); //false
原文:http://www.cnblogs.com/scnuwangjie/p/5002912.html