Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
JS Class method - swapping values between instances

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']
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!