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

205
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
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