I’m doing the Mysterious Organism exercise within the lesson about Objects and there is one bit I’m just not getting.
I create an object that has certain contents.
I copy the source object to a target object.
I make one slight change to the target objection.
I compare for differences.
The problem is I’m not copying the object, I’m simply creating a new variable that addresses the original object. Effective, after I’ve “copied” it, it now has two names.
I’ve attempted to include a screenshot and I hope that worked.
The values in the screenshot are from the quokka.js extension to Visual Studio Code.
To reiterate the steps above, but with more specific details:
- I create org1 via the object factory function pAequorFactory().
- Via console.log, I display the contents of org1.dna.
- I make a copy of org1 to org2
- Via console.log, I display the contents of org2.dna.
- I use the mutate() method to change one letter within org2.dna.
- Via console.log, I display the mutated contents of org2.dna.
- To confirm all is working right, I display the contents of org1.dna.
As you can see, when I use the mutate() method to change one letter within org2.dna, I do in fact change one letter.
The problem is, I also change the same one letter in org1, which indicates to me that org2 and org1 are two different references for the same object, not two different instances of similar objects.
I think what I need to do is create org2 as a true copy of org1, but I thought the Object.assign() method would do that.
Apparently, it didn’t.
Can anyone point me in the right direction?