Setter and Class


#1

class School {
constructor (numberOfStudents) {
this._numberOfStudents = numberOfStudents
}
//getter
get numberOfStudents () {
return this._numberOfStudents
}
//setter
set numberOfStudents (value) {
if (typeof value === ‘string’) {
console.log(‘Invalid input: numberOfStudents must be set to a Number.’)
} else {
this._numberOfStudents = value;
}
}
}

const codeAcademy = new School(“three”);

console.log(codeAcademy) // return ->>> _numberOfStudents: “three”

"Three is not number but how could i assigned the codeAcademy const?

https://www.codecademy.com/paths/web-development/tracks/webdev-intermediate-javascript/modules/learn-javascript-classes/projects/school-catalog


#2

The value being passed in as argument to the new instance is not validated, so 'three' is assigned.

It may seem a bit weird, but we can use the setter in the constructor.

class School {
  constructor (numberOfStudents) {
    this.numberOfStudents = numberOfStudents;
  }
  get numberOfStudents () {
    return this._numberOfStudents
  }
  set numberOfStudents (value) {
    if (typeof value === 'string') {
      console.log('Invalid input: numberOfStudents must be set to a Number.')
    } else {
      this._numberOfStudents = value;
    }
  }
}
 > codecademy = new School('three')
   invalid input: numberOfStudents must be set to a Number.
<- > School {}
 > codecademy = new School(3)
<- > School {_numberOfStudents: 3}

#3

I suppose , problem is underscore :face_with_raised_eyebrow:

For example ;

this .numberOfStudents = numberOfStudents;
codecademy = new School(‘three’)
invalid input: numberOfStudents must be set to a Number.

But, this code result different than above;

this ._numberOfStudents = numberOfStudents;
codecademy = new School(‘three’)
three’ is assigned.

i’m confused, because i learnt that “we should use underscore when we create constructor” , So video’s solution https://www.youtube.com/watch?time_continue=177&v=9p2VeKRKZ1Q 2:51 don’t work :thinking:


#4

In fact we are in the example above. The literal attribute is _numberOfStudents as the output shows. The setter is called from the constructor. The setter doesn’t know whether the attribute exists or not. The act of setting it, creates it if it does not yet exist.

  constructor (numberOfStudents) {
    this.numberOfStudents = numberOfStudents;
    // call to setter          argument
  }

which results in,

        this._numberOfStudents = value;