Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cloning a JavaScript object? [duplicate]

Tags:

javascript

Possible Duplicate:
How to clone js object?

This is another way to create a javascript object (using object literal notation instead of function):

user = {
  name: "Foo",
  email: "[email protected]"
}

Is there a way to clone this object or is it a singleton?

like image 740
never_had_a_name Avatar asked Sep 22 '10 22:09

never_had_a_name


People also ask

Why do we clone object in JavaScript?

Cloning a JavaScript object is a task that is used mostly because we do not want to create the same object if the same object already exists. There are few ways. By iterate through each property and copy them to new object. Using JSON method as the source object MUST be JSON safe.

How do you deep copy an object in JavaScript?

assign() was the most popular way to deep copy an object. Object. assign() will copy everything into the new object, including any functions. Mutating the copied object also doesn't affect the original object.

How many ways we can clone object in JavaScript?

JavaScript provides 3 good ways to clone objects: using spread operator, rest operator and Object.


1 Answers

Try this:

var clone = (function(){ 
  return function (obj) { Clone.prototype=obj; return new Clone() };
  function Clone(){}
}());

Here's what's going on.

  • Clone is a dummy constructor.
  • We assign the object we want to clone to the Clone constructor's prototype.
  • We call Clone using 'new', so the constructed object has the original object as its constructor's prototype aka (non-standard) __proto__.

The cloned object will share all the properties of the original object without any copies of anything being made. If properties of the cloned object are assigned new values, they won't interfere with the original object. And no tampering of built-ins is required.

Keep in mind that an object property of the newly-created object will refer to the same object as the eponymous property of the cloned object. Assigning a new value to a property of the clone won't interfere with the original, but assigning values to the clone's object properties will.


Try this in chrome or firebug console:

var user = {
  name: "Foo",
  email: "[email protected]"
}

var clonedUser = clone(user);

console.dir(clonedUser);

A detailed explanation of this cloning technique can be found here.

like image 94
Dagg Nabbit Avatar answered Oct 26 '22 11:10

Dagg Nabbit