Javascript classes and calling parameters


#1

I’m doing the javascript course and I’ve set up a class as follows:

class Surgeon {
  constructor(name, department) {
    this._name = name;
    this._department = department;
    this._remainingVacationDays = 20;
  }
  
  get name() {
    return this._name;
  }
}

An instance of the surgeon class (surgeonCurry) is created with the name ‘Curry’.

I would have assumed to call the name from outside one would write . . .

console.log(surgeonCurry._name)

. . . seeing as name is the property key for all instances of the surgeon class.

However the solutions writes. . .

console.log(surgeonCurry.name)

This seems to be a calling the getter method in the object.

Both approaches work. Which is better and why?

Thanks,

Stu


#2

Correct. get and set are accessor functions that abstract away actual attribute names, and even keep them from being set (if the actual name is not known) by not giving them a setter.

As for writing this way,

console.log(surgeonCurry._name)

that would be counterproductive. One may as well just stick to the old syntax (no prefix on the property).

get and set allow us to use the old syntax, but in a new way. The advantages are vague (in my case) but I would speculate the powers that be (who write the specifications) believe them to be of great value or they would not have updated the language to include them.

One advantage is that they are methods, after all, which means we can customize their role, add conditions and error messages, etc…

set age (newAge) {
    if (type newAge === 'number') {
        this._age = newAge;
    } else {
        console.log('input error!');
    }
}

Now when we pass an illegal value the method can trap it and inform the user.

Again, it’s pure speculation but when the inputs to a class instance are complex, a getter could unpack it and return it in a more usable form. I won’t continue to speculate, though. You’ll need to do some reading to get a satisfactory answer. When you find one, we hope you’ll share it with us in a reply.