Learning about classes I noticed an interesting phenomenon, can you please explain how it happens. In class Infected I declared a function infect(somebody). In my example of mary.infect(john) - while I understand that Mary gets infected (mary is the object I'm calling the function on, mary is the object I'm currently working on, changing mary's property value), I don't understand how John gets infected from Mary too (john serves as merely an argument in current function call).
In other words: mary.infect(john) - I'm calling this function 'from' mary object (mary is 'this' object), so what kind of magic happens here that I'm able to change the value of John's diseases as well?
My thinking was: if I use john as merely a parameter (argument) in a function call to mary, all I can do is extract certain values from john (like his diseases), but I didn't expect I can at the same moment access john and change john's values. It just seemed a bit counter-intuitive to me.
It's cool we can swap values between two objects like that. But I don't get how it works.
class Infected {
constructor(name, diseases) {
this.name = name;
this.diseases = diseases;
}
infect(somebody) {
const thisDiseases = this.diseases;
this.diseases = this.diseases.concat(somebody.diseases);
somebody.diseases = somebody.diseases.concat(thisDiseases);
}
}
const mary = new Infected('Mary', ['herpes', 'hepatitis']);
const john = new Infected('John', ['flu', 'syphilis']);
mary.infect(john);
mary.diseases -> ['herpes', 'hepatitis', 'flu', 'syphilis']
john.diseases -> ['flu', 'syphilis', 'herpes', 'hepatitis']