call a getter on an instance of a class in javascript

To call a getter on an instance of a JavaScript class, you need to access the particular getter method of that class with the instance variable. Assuming you have a class called Person, and you want to access the name getter of a specific instance variable p, you can do it like this:

index.tsx
class Person {
  constructor(name){
    this._name = name;
  }
  get name() {
    return this._name;
  }
}

const p = new Person('John');
console.log(p.name); // This will log 'John' to the console. 

201 chars
13 lines

Here, we first define a class Person with a name getter which simply returns the _name instance variable of the class.

Then, we create an instance variable p of the Person class with the name 'John'. Finally, we can access the name getter of p by calling p.name, which will return the value of the instance variable _name ('John' in this case).

gistlibby LogSnag