Skip to content

Instantly share code, notes, and snippets.

@sscovil
Created February 22, 2022 21:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sscovil/def81066dc59e6ff5084a499d9855253 to your computer and use it in GitHub Desktop.
Save sscovil/def81066dc59e6ff5084a499d9855253 to your computer and use it in GitHub Desktop.
Example for comment on SO answer: https://stackoverflow.com/a/65024713/630544
/**
* When creating a clone method for a class, keep in mind that object and array properties assigned to the clone
* are passed by reference! This means modifying those properties on the clone will modify them on the original.
* To avoid this, you need to clone the object and array property values as well.
*/
class Foo {
constructor() {
this.arr = []
}
static clone(foo) {
const clone = new Foo()
clone.arr = foo.arr
return clone
}
}
const foo = new Foo()
foo.arr.push('bar')
console.log(foo.arr) // ['bar']
const clone = Foo.clone(foo)
console.log(clone.arr) // ['bar']
foo.arr.push('baz')
console.log(foo.arr) // ['bar', 'baz']
console.log(clone.arr) // ['bar', 'baz']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment