在JavaScript裡,複製對象有「淺」與「深」兩種層次:
1.1 簡單的賦值迴圈
function simpleClone(initalObj) {
var obj = {};
for (var i in initalObj) {
obj[i] = initalObj[i];
}
return obj;
}
客戶端調用:
var obj = {
a: "hello",
b: { a: "world", b: 21 },
c: ["Bob", "Tom", "Jenny"],
d: function() { alert("hello world"); }
};
var cloneObj = simpleClone(obj);
console.log(cloneObj.b); // {a: "world", b: 21}
console.log(cloneObj.c); // ["Bob", "Tom", "Jenny"]
// 修改拷貝後的對象
cloneObj.b.a = "changed";
cloneObj.c = [1, 2, 3];
cloneObj.d = function() { alert("changed"); };
console.log(obj.b); // {a: "changed", b: 21} —— 原對象的 b 被連帶改動了
console.log(obj.c); // ["Bob", "Tom", "Jenny"]
console.log(obj.d); // function() { alert("hello world"); }
可以看到,修改 cloneObj 的嵌套對象 b 時,原對象的 b 也跟著變了,這正是淺拷貝的特性。
1.2 Object.assign()
Object.assign() 能把多個來源對象的可枚舉屬性複製到目標對象並回傳,但它同樣是淺拷貝,複製的是屬性的引用:
var obj = { a: {a: "hello", b: 21} };
var initalObj = Object.assign({}, obj);
initalObj.a.a = "changed";
console.log(obj.a.a); // "changed"
2.1 使用 JSON.parse()
function deepClone(initalObj) {
var obj = {};
try {
obj = JSON.parse(JSON.stringify(initalObj));
} catch(e) {}
return obj;
}
這種寫法簡單易用,但也有明顯限制:它會丟棄對象的 constructor(深拷貝後一律變成 Object),而且只能正確處理 Number、String、Boolean、Array 與扁平對象等能被 JSON 直接表達的結構,像 RegExp 就無法用這招複製。
2.2 遞歸拷貝
function deepClone(initalObj, finalObj) {
var obj = finalObj || {};
for (var i in initalObj) {
if (typeof initalObj[i] === 'object') {
obj[i] = (initalObj[i].constructor === Array) ? [] : {};
arguments.callee(initalObj[i], obj[i]);
} else {
obj[i] = initalObj[i];
}
}
return obj;
}
它能實現深拷貝,但遇到兩個互相引用的對象時會陷入死循環。為避免這種情況,可在遍歷時判斷是否指向自身並跳出:
function deepClone(initalObj, finalObj) {
var obj = finalObj || {};
for (var i in initalObj) {
var prop = initalObj[i];
// 避免相互引用導致死循環,如 initalObj.a = initalObj
if (prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === Array) ? [] : {};
arguments.callee(prop, obj[i]);
} else {
obj[i] = prop;
}
}
return obj;
}
2.3 使用 Object.create()
function deepClone(initalObj, finalObj) {
var obj = finalObj || {};
for (var i in initalObj) {
var prop = initalObj[i];
if (prop === obj) {
continue;
}
if (typeof prop === 'object') {
obj[i] = (prop.constructor === Array) ? [] : Object.create(prop);
} else {
obj[i] = prop;
}
}
return obj;
}
jQuery 的 jQuery.extend() 也實作了深拷貝,官方原始碼可參考:https://github.com/jquery/jquery/blob/master/src/core.js。
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[ 0 ] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[ i ] || {};
i++;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction( target ) ) {
target = {};
}
// Extend jQuery itself if only one argument is passed
if ( i === length ) {
target = this;
i--;
}
for ( ; i < length; i++ ) {
if ( ( options = arguments[ i ] ) != null ) {
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject( copy ) ||
( copyIsArray = jQuery.isArray( copy ) ) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray( src ) ? src : [];
} else {
clone = src && jQuery.isPlainObject( src ) ? src : {};
}
target[ name ] = jQuery.extend( deep, clone, copy );
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
return target;
};