Skip to content

Instantly share code, notes, and snippets.

@phlik
Created January 6, 2013 05:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phlik/4465406 to your computer and use it in GitHub Desktop.
Save phlik/4465406 to your computer and use it in GitHub Desktop.
Showing a way to make a clone of a object in javascript
<html>
<body>
<div id="con"></div>
</body>
</html>
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);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment