Johann Davel De Beer
Johann Davel De Beer

Reputation: 51

Implementation of get and set in a class

Im going through w3s and found this. https://www.w3schools.com/Js/tryit.asp?filename=tryjs_classes_getters

I understand the path all the values take but how would this be implemented/why does get set in classes get used? I learn by implementing and i would greatly appreciate an example.

Upvotes: 1

Views: 54

Answers (1)

GirkovArpa
GirkovArpa

Reputation: 4912

One possible use is validation. Imagine the class Account implemented this way:

class Account {
  #username;
  #password;
  constructor(name) {
    this.#username = name;
  }
  get username() {
    return this.#username;
  }
  set password(password) {
    if (password.length < 10) {
      throw "Password must be at least 10 characters long!";
    }
    this.#password = password;
  }
  get password() {
    throw "Forgotten passwords cannot be retrieved!  Please make a new one instead.";
  }
}

I can make a new account like this:

const myAccount = new Account('John Doe');

If I try to set the password to an unacceptably short length, I will get an error:

myAccount.password = 'hunter2'; // Password must be at least 10 characters long!

If I try to retrieve my password after forgetting it, I will again get an error:

console.log(myAccount.password); // Forgotten passwords cannot be retrieved!  Please make a new one instead.

Upvotes: 2

Related Questions