Saturday, January 5, 2013

deep copy in javascript

One of the things about javascript I don't like is that there is not a simple way to copy an object literal so you don't have side effects when making updates to an object. this script show how I got around this.
<html>
<body>
<div id="con"></div>
</body>
</html>
view raw deepCopy.html hosted with ❤ by GitHub
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);
view raw deepCopy.js hosted with ❤ by GitHub
There is alos a fiddle as well which can be found here

No comments: