JavaScript中的對象複製(Object Clone)

來源:互聯網
上載者:User

標籤:

JavaScript中並沒有直接提供對象複製(Object Clone)的方法。因此下面的代碼中改變對象b的時候,也就改變了對象a。

a = {k1:1, k2:2, k3:3};b = a;b.k2 = 4;

如果只想改變b而保持a不變,就需要對對象a進行複製。

用jQuery進行對象複製

在可以使用jQuery的情況下,jQuery內建的extend方法可以用來實現對象的複製。

a = {k1:1, k2:2, k3:3};b = {};$.extend(b,a);
自訂clone()方法來實現對象複製

下面的方法,是對象複製的基本想法。

Object.prototype.clone = function() {  var copy = (this instanceof Array) ? [] : {};  for (attr in this) {    if (!obj.hasOwnProperty(attr)) continue;    copy[attr] = (typeof this[i] == "object")?obj[attr].clone():obj[attr];  }   return copy;};a = {k1:1, k2:2, k3:3};b = a.clone();

下面的例子則考慮的更全面些,適用於大部分對象的深度複製(Deep Copy)。

function clone(obj) {    // Handle the 3 simple types, and null or undefined    if (null == obj || "object" != typeof obj) return obj;    // Handle Date    if (obj instanceof Date) {        var copy = new Date();        copy.setTime(obj.getTime());        return copy;    }    // Handle Array    if (obj instanceof Array) {        var copy = [];        for (var i = 0, var len = obj.length; i < len; ++i) {            copy[i] = clone(obj[i]);        }        return copy;    }    // Handle Object    if (obj instanceof Object) {        var copy = {};        for (var attr in obj) {            if (obj.hasOwnProperty(attr)) copy[attr] = clone(obj[attr]);        }        return copy;    }    throw new Error("Unable to copy obj! Its type isn‘t supported.");}
網路資源
  • Copying an Object in Javascript


JavaScript中的對象複製(Object Clone)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.