title: How to deep-copy closure objects (private objects) while Deep Copying
body: <pre><code>    Board = function()
      {
          var  cells = [8];
  
  
          /**
           * Initializing every cell using numeric format.
           * */
          for (var i=0 ; i&lt;8; i++){
              cells[i] = [8];
              for (var j=0 ; j&lt;8; j++)
                  cells[i][j] = new Cell(new Position(i,j));
          }
  
                  ....
  }
  </code></pre>
  
  <p>In Another code GameManager.js,</p>
  
  <pre><code>var duplicateBoard = Copy.deepCopy(board);
  board.moveCell(1,2)
  </code></pre>
  
  <p>And for Deepcopying I am using,</p>
  
  <p>Ref : <a href="http://jsperf.com/deep-copy-vs-json-stringify-json-parse" rel="nofollow">http://jsperf.com/deep-copy-vs-json-stringify-json-parse</a></p>
  
  <pre><code> function deepCopy(o) {
          var copy = o,k;
  
          if (o &amp;&amp; typeof o === 'object') {
              copy = Object.prototype.toString.call(o) === '[object Array]' ? [] : {};
              for (k in o) {
                  copy[k] = deepCopy(o[k]);
              }
          }
  
          return copy;
      }
  </code></pre>
  
  <p><strong>My need : <br></strong>
          I want <code>cells</code> (private member of constructor ) in <code>Board</code> to be deep-copied.</p>
  
  <p><strong>Problem :</strong> <br>
  But, When I debugged with firebug, I saw, <code>deepCopy</code> function does not deep copying <strong>private objects of constructor.</strong> <br></p>
  
  <p><strong>My Case :</strong> <br>
  <code>board.moveCell(1,2)</code>, Here cell[1][2] is moved in <code>duplicateBoard</code> too. <br>
  That is,
  No deep-copying of <code>cell</code> has taken place
  Both the board and duplicateBoard has same reference to cell[1][2].</p>
  
  <p><strong>What I have traced ?</strong>
   The deep-copy function, treats the <code>constructor</code> to be a function, hence it ignores deep-copying the functions, since it will fail in <code>typeof o === 'object</code>. But removing this condition is not useful, because by doing so, <code>duplicateBoard</code> has no functions rather all the functions to be <code>object{}</code> type.</p>