Skip to content
Categories:

Clone object using jQuery.extend() in javascript

Post date:

在 Javascript 中,如何複製物件?

一般情況下都會想使用 = 的方式來複製,不過可能會得到以下結果:

var obj = {'a': 1, 'b': 2};
var new_obj = obj;
new_obj.c = 3;

//result
obj = {'a': 1, 'b': 2, 'c': 3};


新物件是有了原始物件的內容沒錯,但是一修改到 new_obj 物件內容, obj 也會跟著異動。

原因是這種方式會變成 reference,所以行不通,而 jQuery 所提供的 clone() 僅適用於 DOM 的複製。

不過還是可以使用 jQuery.extend() 方法來達成:

/*
 * clone object by jQuery.extend (deep copy)
 * @param: source / 來源物件
 * @param: append / 附加的值 (非必要)
 */
function clone (source, append) {
  if ('undefined' !== typeof append) {
    var obj = jQuery.extend({}, source);
    return jQuery.extend(true, obj, append);
  } else {
    return jQuery.extend(true, {}, source);
  }
}

//run
var obj = {'a': 1, 'b': 2};
var new_obj = clone(obj, {'c': 3});

//result
obj = {'a': 1, 'b': 2};
new_obj = {'a': 1, 'b': 2, 'c': 3};

延伸閱讀:


讀過幾年書,塵世中的迷途大叔。

Comments

  • var obj = {‘a’: 1, ‘b’: 2};

    var new_obj = new Object();

    function cloneObj(source, destination, appendProperties){
    for(idx in source){
    destination[idx] = source[idx];
    }
    for(idx in destination){
    if(source[idx] == null){
    delete destination[idx];
    }
    }
    if(appendProperties != null){
    for(idx in appendProperties){
    destination[idx] = appendProperties[idx];
    }
    }
    }

    cloneObj(obj, new_obj);

    console.log(obj);console.log(new_obj);
    Object {a: 1, b: 2}
    Object {a: 1, b: 2}

    new_obj.c = 3;

    console.log(obj);console.log(new_obj);
    Object {a: 1, b: 2}
    Object {a: 1, b: 2, c: 3}

    cloneObj(obj, new_obj);

    console.log(obj);console.log(new_obj);
    Object {a: 1, b: 2}
    Object {a: 1, b: 2}

    cloneObj(obj,new_obj, { c:3, d:4, e:5});
    Object {a: 1, b: 2}
    Object {a: 1, b: 2, c: 3, d: 4, e: 5}