Skip to content

Instantly share code, notes, and snippets.

@ebonneville
Created May 22, 2012 00:08
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 ebonneville/2765582 to your computer and use it in GitHub Desktop.
Save ebonneville/2765582 to your computer and use it in GitHub Desktop.
Clones an object and returns the clone.
// recursive function to clone an object. If a non object parameter
// is passed in, that parameter is returned and no recursion occurs.
function cloneObject(obj) {
if (obj === null || typeof obj !== 'object') {
return obj;
}
var temp = obj.constructor(); // give temp the original obj's constructor
for (var key in obj) {
temp[key] = cloneObject(obj[key]);
}
return temp;
}
var bob = {
name: "Bob",
age: 32
};
var bill = (cloneObject(bob));
bill.name = "Bill";
console.log(bob);
console.log(bill);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment