Home > OS >  Javascript: allow certain classes to change properties of another class
Javascript: allow certain classes to change properties of another class

Time:04-19

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)
 }
}

CodePudding user response:

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());
  • Related