Member-only story
Getters and setters are special methods in JavaScript classes that allow you to control access to class properties. They provide a way to define computations or validations whenever a property is accessed or modified.
In this article, we’ll explore how to use getters and setters in JavaScript classes with clear, concise examples.
Let’s start with a simple example of a Person
class:
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
}
const person = new Person('Alice', 25);
console.log(person._name); // Alice
console.log(person._age); // 25
In this example, we have direct access to the _name
and _age
properties. However, it's generally considered good practice to use getters and setters to control access to these properties.
Here’s how we can add a getter and setter for the name
property:
class Person {
constructor(name, age) {
this._name = name;
this._age = age;
}
get name() {
return this._name;
}
set name(newName) {
// We can add validation or other logic here
this._name = newName;
}
}
const person =…