Created
September 18, 2014 15:34
-
-
Save seebz/9835ddd270277a0d6827 to your computer and use it in GitHub Desktop.
Object.clone()
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
| 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