add a setter to a class in javascript

You can add a setter method to a class in JavaScript using the set keyword. Here's an example:

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

  // Getter
  get name() {
    return this._name;
  }

  // Setter
  set name(newName) {
    this._name = newName;
  }
}

// Usage
const john = new Person('John');
console.log(john.name); // Output: 'John'
john.name = 'Jane';
console.log(john.name); // Output: 'Jane'
333 chars
22 lines

In the example above, we defined a Person class with a private property _name. We added a getter method get name() to retrieve the _name property value and a setter method set name() to change the value of _name.

Note that the setter method name must match the property name that you want to set, and it should not start with an underscore. Also, you can choose to not include a getter method to hide the private property completely.

related categories

gistlibby LogSnag