Skip to content

Instantly share code, notes, and snippets.

@shcyiza
Last active May 28, 2019 07:19
Show Gist options
  • Save shcyiza/910c84a5f5d27ad5aa8cfad0b926db67 to your computer and use it in GitHub Desktop.
Save shcyiza/910c84a5f5d27ad5aa8cfad0b926db67 to your computer and use it in GitHub Desktop.
shallow and deep clone objects with inheritance
// 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