Skip to content

Instantly share code, notes, and snippets.

@ClementNerma
Created March 19, 2016 22:17
Show Gist options
  • Save ClementNerma/36dbe249e8e5f783e57d to your computer and use it in GitHub Desktop.
Save ClementNerma/36dbe249e8e5f783e57d to your computer and use it in GitHub Desktop.
/**
* Clone an object, contains fixes for the Radu Simionescu's clone function
* http://stackoverflow.com/questions/728360/most-elegant-way-to-clone-a-javascript-object?page=2&tab=active#tab-top
* @param {*} oReferance
* @return {*}
*/
var clone = function(oReferance) {
var aReferances = new Array();
var getPrototypeOf = function(oObject) {
if(typeof(Object.getPrototypeOf)!=="undefined")
return Object.getPrototypeOf(oObject);
var oTest = new Object();
if(typeof(oObject.__proto__)!=="undefined" && typeof(oTest.__proto__)!=="undefined" && oTest.__proto__===Object.prototype)
return oObject.__proto__;
if(typeof(oObject.constructor)!=="undefined" && typeof(oTest.constructor)!=="undefined" && oTest.constructor===Object && typeof(oObject.constructor.prototype)!=="undefined")
return oObject.constructor.prototype;
return Object.prototype;
};
var recursiveCopy = function(oSource) {
if(typeof(oSource)!=="object")
return oSource;
if(oSource===null)
return null;
for(var i = 0; i < aReferances.length; i++)
if(aReferances[i][0]===oSource)
return aReferances[i][1];
if(Array.isArray(oSource)) {
var oCopy = [];
oCopy.prototype = getPrototypeOf(oSource);
aReferances.push([oSource, oCopy]);
for(var k in oSource)
oCopy[k] = recursiveCopy(oSource[k]);
} else {
var Copy = new Function();
Copy.prototype = getPrototypeOf(oSource);
var oCopy = new Copy();
aReferances.push([oSource,oCopy]);
for(var sPropertyName in oSource) {
if(oSource.hasOwnProperty(sPropertyName))
oCopy[sPropertyName] = recursiveCopy(oSource[sPropertyName]);
}
}
return oCopy;
};
return recursiveCopy(oReferance);
};
/* === Demo === */
var event = {date: '06/12/16', content: 'Eat some hamburger'}; // {... content: Go to school}
var copy1 = event;
var copy2 = clone(event);
copy1.content = 'Eat some cheese';
console.log(event.content); // 'Eat some cheese'
copy2.content = 'nothing';
console.log(event.content); // 'Eat some cheese', not modified because that's a clone
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment