Last active
February 22, 2022 00:12
-
-
Save blarfoon/c8abd25f00e71942d9900ef90f878d17 to your computer and use it in GitHub Desktop.
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 clone(src) { | |
const ret = src instanceof Array ? [] : {}; | |
for (const key in src) { | |
if (!src.hasOwnProperty(key)) { | |
continue; | |
} | |
let val = src[key]; | |
if (val && typeof val == "object") { | |
val = clone(val); | |
} | |
ret[key] = val; | |
} | |
return ret; | |
} | |
const myObject = { | |
hi: "mom", | |
changeHi() { | |
this.hi = "medium"; | |
}, | |
something: undefined, | |
}; | |
console.log(myObject); // > {hi: "mom", something: undefined, changeHi: ƒ} | |
const myNewObject = clone(myObject); | |
myNewObject.changeHi(); | |
console.log(myNewObject); // > {hi: "medium", something: undefined, changeHi: ƒ} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment