add a getter to a subclass in javascript

To add a getter to a subclass in JavaScript, you can use the Object.defineProperty() method to define a property on the subclass prototype.

index.tsx
class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

class Employee extends Person {
  constructor(name, age, salary) {
    super(name, age);
    this.salary = salary;
  }

  getSalary() {
    return this.salary;
  }
}

Object.defineProperty(Employee.prototype, 'fullName', {
  get: function() { return this.name; }
});

const employee = new Employee('John Doe', 30, 50000);
console.log(employee.fullName); // Output: John Doe
console.log(employee.getSalary()); // Output: 50000
517 chars
26 lines

In this example, we define a getter for the fullName property on the Employee subclass prototype using Object.defineProperty(). The get function returns the name property of the instance. Then we create an instance of the Employee subclass and call fullName and getSalary() to test the getter and the method.

gistlibby LogSnag