Cloning an object in javascript.

When you need to create a copy of an object that has sub objects. And you want all the objects to be free of there orgional memmory space

by Erin Houston

HTML

<div id="con"></div>

JavaScript

function printLog(text, element) {
  var ni = document.getElementById('con');
  var newdiv = document.createElement('div');
  var outText = element ? " " + JSON.stringify(element) : "";
  newdiv.innerHTML = text + outText;
  ni.appendChild(newdiv);
}


function deepCopy(org) {
  return JSON.parse(JSON.stringify(org));
}

var objectThatGetsChanged = {
  name: "ping"
};

var objectThatDosntChange = {
  name: "pong"
};

function changeNameWithSideEffects(person, newName) {
  person.name = newName;
  return person;
}

function changeNameWithOutSideEffects(person, newName) {
  var workingStiff = deepCopy(person);
  workingStiff.name = newName;
  return workingStiff;
}

printLog("<br /><hr /><br />");
printLog("Show an function that changes state of the exsising object");
printLog("objectThatGetsChanged before change", objectThatGetsChanged);
var result = changeNameWithSideEffects(objectThatGetsChanged, "ball");
printLog("result object", result);
printLog("objectThatGetsChanged after change", objectThatGetsChanged);

printLog("<br /><hr /><br />");
printLog("Show an function that does not changes state of the exsising object");
printLog("objectThatDosntChange before change", objectThatDosntChange);
var result2 = changeNameWithOutSideEffects(objectThatDosntChange, "paddle");
printLog("result2 object", result2);
printLog("objectThatDosntChange after change", objectThatDosntChange);