Hi,
I am on the classes part of the course and I really don’t understand something about setters.
class School {
constructor(name, level, numberOfStudents) {
this._name = name;
this._level = level;
this._numberOfStudents = numberOfStudents;
}
set numberOfStudents(number) {
if (typeof number === "Number") {
this._numberOfStudents = number;
} else {
console.log('Invalid input: numberOfStudents must be set to a Number.');
}
}
class High extends School {
constructor(name, numberOfStudents, sportsTeam) {
super(name, 'high', numberOfStudents);
this._sportsTeam = sportsTeam;
}
get sportsTeam() {
return this._sportsTeam;
}
}
These are the getters and setters and below is creating an instance.
//create an instance of the class
const alSmith = new High('Al E. Smith', 500, ['Baseball', 'Basketball', 'Volleyball', 'Track and Field'])
// try to change the number of students
alSmith.numberOfStudents = 415; // sets numberOfStudents to 415
//try to set as an incorrect value
alSmith.numberOfStudents = 'apple'; //logs 'Invalid input: numberOfStudents must be set to a Number.' as expected.
This is all fine but I don’t really see how it’s that useful because we set the values upon initializing the instance.
const alSmith = new High('Al E. Smith', 500, ['Baseball', 'Basketball', 'Volleyball', 'Track and Field'])
console.log(alSmith.numberOfStudents); // returns 500
const alSmith = new High('Al E. Smith', 'apple', ['Baseball', 'Basketball', 'Volleyball', 'Track and Field'])
console.log(alSmith.numberOfStudents); // returns 'apple'
Obviously when we initialise the instance we want to make sure that out data is clean, I thought that this is why we used setters. But when I make the new instance I can set whatever value i like as numberOfStudents and it won’t throw an error message. Can someone tell me why this is? And how you would use a setter when you initialise an instance?