add a getter to a class in javascript

To add a getter to a JavaScript class, use the get keyword before the method name in the class definition. The method should return the value that you want to access. Here's an example:

class Person {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  get fullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

const person1 = new Person('John', 'Doe');
console.log(person1.fullName); // Output: 'John Doe'
290 chars
14 lines

In this example, the Person class has a fullName getter that returns the full name of the person. The fullName getter does not have any parameters and is accessed just like a regular property. When you call person1.fullName, the getter is invoked and the full name of person1 is returned.

gistlibby LogSnag