Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

169
Vistas
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
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda