Created
February 22, 2022 21:01
-
-
Save sscovil/def81066dc59e6ff5084a499d9855253 to your computer and use it in GitHub Desktop.
Example for comment on SO answer: https://stackoverflow.com/a/65024713/630544
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
/** | |
* 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