js why to use getters and setters code example

Example 1: getters and setters javascript classes

// ES6 get and set
class Person {
  constructor(name) {
    this._name = name;
  }

  get name() {
    return this._name.toUpperCase();
  }

  set name(newName) {
    this._name = newName; // validation could be checked here such as only allowing non numerical values
  }

  walk() {
    console.log(this._name + ' is walking.');
  }
}

let bob = new Person('Bob');
console.log(bob.name); // Outputs 'BOB'

Example 2: javascript getters and setters

/*Getter functions are meant to simply return (get) the value of an object's 
private variable to the user without the user directly accessing the private 
variable.*/
/*Setter functions are meant to modify (set) the value of an object's private 
variable based on the value passed into the setter function. This change could
involve calculations, or even overwriting the previous value completely.*/
class Book {
  constructor(author) {
    this._author = author;
  }
  // getter
  get writer() {
    return this._author;
  }
  // setter
  set writer(updatedAuthor) {
    this._author = updatedAuthor;
  }
}
const novel = new Book('anonymous');
console.log(novel.writer);  // anonymous
novel.writer = 'newAuthor';
console.log(novel.writer);  // newAuthor

Example 3: js why to use getters and setters

1) Syntax reasons. It’s easier and faster to read code 
created with accessor functions
2) Encapsulation. I can create safer code with accessor functions.

Tags:

Java Example