Last active
October 12, 2022 09:20
-
-
Save bertolo1988/c7c08993d94ec88617018f39ec330842 to your computer and use it in GitHub Desktop.
How to clone a javascript object without just referencing the prototype.
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
// How to clone a javascript object without just referencing the prototype | |
const assert = require('node:assert') | |
const input = { a: 1 } | |
// every prototype is an object with normal property descriptors | |
const prototypeDescriptors = Object.getOwnPropertyDescriptors( | |
Object.getPrototypeOf(input) | |
) | |
// this creates an object without prototype using the property | |
// descriptors of input.__proto__ | |
const protoClone = Object.create(null, prototypeDescriptors) | |
// this clones input but assigns our protoClone as our __proto__ | |
const inputClone = Object.create( | |
protoClone, | |
Object.getOwnPropertyDescriptors(input) | |
) | |
// proof that inputClone is a clone of input without just referencing the prototype | |
assert.ok(inputClone !== input) | |
assert.ok(Object.getPrototypeOf(inputClone) !== Object.getPrototypeOf(input)) | |
Object.getPrototypeOf(input).foo = 'bar' | |
assert.ok(Object.getPrototypeOf(inputClone).foo === undefined) | |
assert.equal(inputClone.a, input.a) | |
console.log('voilá, a real clone') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment