开发者

How to clone js object? [duplicate]

开发者 https://www.devze.com 2023-01-11 15:43 出处:网络
This question already has answers here: Closed 10 years ago. Possible Duplicate: What is the most efficient way to clone a JavaScript object?
This question already has answers here: Closed 10 years ago.

Possible Duplicate:

What is the most efficient way to clone a JavaScript object?

How to clone js object with out 开发者_运维技巧reference like these:

{ ID: _docEl,
  Index: next,
  DocName: _el
}

Any ideas?


Edit: New visitors should probably head to this question. There is a new (as of this writing) browser supported function called structuredClone() that will be useful as browsers and engines adopt it.

Still consider the additional considerations I write below:


You'll have to iterate over the object and make copies of all its properties.

And then if any of its properties are also objects, assuming you want to clone those too, you'll have to recurse into them.

There's various methods for doing this here: What is the most efficient way to clone a JavaScript object?

Doing this isn't a perfect copy - depending on how it's done the new object won't inherit the original object's relationship to its prototype and you won't be able to maintain the same distinction between copied properties that were from the prototypal chain or from the object itself. And built-in objects (like DOM nodes) won't copy properly. In the case of DOM nodes you can clone those with their own cloneNode().

Additional considerations

Consider whether your application really needs to clone the object or whether some other design might be appropriate.

Cloning an object by copying all its properties will create two separate copies of all its properties, and if you modify one's properties the other object won't change. If you don't need this to be the case, simply copying the object will suffice.

You can also consider using prototypes (or the newer class syntax) and new which effectively creates objects with a set of properties from a prototype that can be overridden naturally or have fall-back to those in the prototype.

Or, finally, if you wanted to add properties or methods to the new object without affecting the original object, can you just encapsulate object A into object B, that is, have object A as a property in object B, so that you can still get the reference to the original object as b.a.property, but can add properties to b alone as b.property.


Here's how I'd do it, based on thomasrutter's suggestion (untested code):

function cloneObj(obj) {
    var clone = {};

    for (var i in obj) {
        if (obj[i] && typeof obj[i] == 'object') {
            clone[i] = cloneObj(obj[i]);
        } else {
            clone[i] = obj[i];
        }
    }

    return clone;
}


You can use jQuery.extend:

// Shallow copy
var newObject = jQuery.extend({}, oldObject);

// Deep copy
var newObject = jQuery.extend(true, {}, oldObject);

The following post is so helpful:

What is the most efficient way to deep clone an object in JavaScript?


JavaScript JS object clone

Object._clone = function(obj) {
  var clone, property, value;
  if (!obj || typeof obj !== 'object') {
    return obj;
  }
  clone = typeof obj.pop === 'function' ? [] : {};
  clone.__proto__ = obj.__proto__;
  for (property in obj) {
    if (obj.hasOwnProperty(property)) {
      value = obj.property;
      if (value && typeof value === 'object') {
        clone[property] = Object._clone(value);
      } else {
        clone[property] = obj[property];
      }
    }
  }
  return clone;
};

CoffeeScript JS object clone

# Object clone
Object._clone = (obj) ->
  return obj if not obj or typeof(obj) isnt 'object'
  clone = if typeof(obj.pop) is 'function' then [] else {}

  # deprecated, but need for instanceof method
  clone.__proto__ = obj.__proto__

  for property of obj
    if obj.hasOwnProperty property
      # clone properties
      value = obj.property
      if value and typeof(value) is 'object'
        clone[property] = Object._clone(value)
      else
        clone[property] = obj[property]

  clone

Now you can try to do that

A = new TestKlass
B = Object._clone(A)
B instanceof TestKlass => true


function objToClone(obj){
  return (new Function("return " + obj))
}
0

精彩评论

暂无评论...
验证码 换一张
取 消