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

203
Visualizações
Javascript: allow certain classes to change properties of another class

I have Student class. The student has a grade. Teacher class can change the student's grade. Other classes (i.e., parent class) cannot do that. I think I get the part about how to change another class's property (please correct me if I'm wrong), but how to make sure that only the Teacher class can change the grade?

class Student {
 grade = 'A';

 changeGrade(grade) {
  this.grade = grade
  return `the new grade is ${this.grade}`
 }
}

class Teacher {
 changeStudentGrade(student, grade) {
  return student.changeGrade(grade)
 }
}
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

JavaScript does not support this functionality. However, you can still add suitable logic to facilitate it by checking the class that is trying to changeGrade within the method as follows:

changeGrade(grade, classChangingGrade) {
   if (classChangingGrade instanceof Teacher) {
     this.grade = grade
      return `the new grade is ${this.grade}`
   }
 }

Then this method should be invoked as below:

return student.changeGrade(grade, this);

Disclaimer

Other classes can get around this by creating a new Teacher instance and invoking changeGrade as follows:

student.changeGrade(grade, new Teacher());
about 4 years ago · Juan Pablo Isaza Relatório
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