Note that there are some explanatory texts on larger screens.

plurals
  1. POHow to Deep clone in javascript
    primarykey
    data
    text
    <p>How do you deep clone a Javascript object?</p> <p>I know there are various functions based on frameworks like <code>JSON.parse(JSON.stringify(o))</code> and <code>$.extend(true, {}, o)</code> but I don't want to use a framework like that.</p> <p>What is the most elegant or efficient way to create a deep clone. </p> <p>We do care about edge cases like cloning array's. Not breaking prototype chains, dealing with self reference.</p> <p>We don't care about supporting copying of DOM objects and like because <code>.cloneNode</code> exists for that reason.</p> <p>As I mainly want to use deep clones in <code>node.js</code> using ES5 features of the V8 engine is acceptable. </p> <p>[Edit]</p> <p>Before anyone suggests let me mention there is a distinct difference between creating a copy by prototypically inheriting from the object and <em>cloning</em> it. The former makes a mess of the prototype chain.</p> <p>[Further Edit]</p> <p>After reading your answer I came to the annoying discovery that cloning entire objects is a very dangerous and difficult game. Take for example the following closure based object</p> <pre><code>var o = (function() { var magic = 42; var magicContainer = function() { this.get = function() { return magic; }; this.set = function(i) { magic = i; }; } return new magicContainer; }()); var n = clone(o); // how to implement clone to support closures </code></pre> <p>Is there any way to write a clone function that clones the object, has the same state at time of cloning but cannot alter the state of <code>o</code> without writing a JS parser in JS.</p> <p>There should be no real world need for such a function anymore. This is mere academic interest.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload