0

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)
 }
}
Present practice
  • 601
  • 2
  • 15
  • 27
  • Seems like a duplicate of https://stackoverflow.com/questions/45847399/friend-class-in-typescript – jcalz Apr 18 '22 at 20:50

1 Answers1

1

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());
Ovidijus Parsiunas
  • 2,512
  • 2
  • 8
  • 18