You can add a setter method to a class in JavaScript using the set
keyword. Here's an example:
index.tsx333 chars22 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.
gistlibby LogSnag