浅拷贝
<script type="text/javascript">
var oOriginal = {
memNum: 1, // number
memStr: "I am a string", // string
memObj: {
test1: "Old value" // we'll test
},
memArr: [
"a string",
{
test2: "Try changing me"
}
]
};
var extend = function (result, source) {
for (var key in source)
result[key] = source[key];
return result;
}
var oCopy = extend({}, oOriginal); // 浅拷贝
oCopy.memObj.test1 = "New value"; // 出现问题了,会反射到原对象上
alert(oOriginal.memObj.test1); // 结果副本与原本都一同被修改了
oCopy.memArr[1].test2 = "I am changed";
alert(oOriginal.memArr[1].test2); // 同样中招了
</script>
深拷贝
<script type="text/javascript">
var oOriginal = {
memNum: 1, // number
memStr: "I am a string", // string
memObj: {
test1: "Old value" // we'll test
},
memArr: [
"a string",
{
test2: "Try changing me"
}
]
};
dom = {};
dom.is = function (obj, type) {
var toString = Object.prototype.toString, undefined;
return (type === "Null" && obj === null) ||(type === "Undefined" && obj === undefined) ||toString.call(obj).slice(8, -1) === type;
};
dom.deepCopy = function (result, source) {
for (var key in source) {
var copy = source[key];
if (result === copy) continue; //如window.window === window,会陷入死循环
if (dom.is(copy, "Object")) {
result[key] = arguments.callee(result[key] || {}, copy);
} else if (dom.is(copy, "Array")) {
result[key] = arguments.callee(result[key] || [], copy);
} else {
result[key] = copy;
}
}
return result;
};
var oCopy = dom.deepCopy({}, oOriginal);
oCopy.memObj.test1 = "New value";
alert(oOriginal.memObj.test1);
oCopy.memArr[1].test2 = "I am changed";
alert(oOriginal.memArr[1].test2);
</script>