Skip to content

Instantly share code, notes, and snippets.

@seebz
Created September 18, 2014 15:34
Show Gist options
  • Select an option

  • Save seebz/9835ddd270277a0d6827 to your computer and use it in GitHub Desktop.

Select an option

Save seebz/9835ddd270277a0d6827 to your computer and use it in GitHub Desktop.
Object.clone()
Object.clone = function(obj) {
var type = typeof(obj);
if (obj instanceof Date) {
return new Date(obj.getTime());
}
else if (obj instanceof Array) {
return obj.slice(0);
}
else if (type == "string") {
return "" + obj;
}
else if (type == "number") {
return 0 + obj;
}
else if (type == "object") {
var clone = new obj.constructor;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
clone[key] = Object.clone(obj[key]);
}
}
return clone;
}
else {
return obj;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment