Created
January 6, 2013 05:20
-
-
Save phlik/4465406 to your computer and use it in GitHub Desktop.
Showing a way to make a clone of a object in javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<body> | |
<div id="con"></div> | |
</body> | |
</html> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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