Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

168
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda