JavaScript Getters and Setters Tutorial

In this section, we will learn what the class getters and setters are and how they work in JavaScript.

Note: we’re assuming you’re already read the setter and getter section.

What are Getters and Setters in JavaScript? (Accessor Methods in JavaScript)

The use of getters and setters in Classes is pretty much the same as what we’ve explained for getters and setters in object literals.

Also, getters and setters are accessible via the objects that are created from the target class.

Example: using setters and getters in JavaScript Class

class Person{
  constructor (firstName, lastName){
    this.firstName = firstName; 
    this.lastName = lastName;
  }
  get fullName(){
    return `The fullName is: ${this.firstName} ${this.lastName}`
  }
  set changeName(firstName){
    this.firstName = firstName;
  }
}

const prs1 = new Person("John","Doe");
console.log(prs1.fullName);
prs1.changeName = "Omid";
console.log(prs1.fullName); 

Output:

The fullName is: John Doe

The fullName is: Omid Doe

This Post Has One Comment

  1. Online Casino

    Greetings! Very helpful advice in this particular article!
    It’s the little changes whihh will make the biggest changes.
    Thanks for sharing!

Leave a Reply