Last active
May 28, 2019 07:19
-
-
Save shcyiza/910c84a5f5d27ad5aa8cfad0b926db67 to your computer and use it in GitHub Desktop.
shallow and deep clone objects with inheritance
This file contains 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
// shallow copy | |
function cloneWithProto (source, target = {}) { | |
// if you just want to copy the source the target is optional | |
let clone = {...source, ...target} | |
// make shallow copy out of source, and overwrite with target | |
Object.setPrototypeOf(clone, Object.getPrototypeOf(source)) | |
// set the proto of result to the proto of source object | |
return clone | |
} | |
// deep copy | |
function deepCloneWithProto (source, target = {}) { | |
const clone_source = JSON.parse(JSON.stringify(source)) | |
// deep clone source | |
const clone_target = JSON.parse(JSON.stringify(target)) | |
// deep clone target | |
let result_clone = {...clone_source, ...clone_target} | |
// concatenate the deep clones together | |
Object.setPrototypeOf(result_clone, Object.getPrototypeOf(source)) | |
// set the proto of result_clone to the proto of source object | |
// and not the deep clone of source | |
return result_clone | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment