Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading