Getters (get
) and setters (set
) allow controlled access to properties.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
get fullName() {
return `${this.brand} ${this.model}`;
}
set updateModel(newModel) {
this.model = newModel;
}
}
const car1 = new Car("Tesla", "Model 3");
console.log(car1.fullName); // Output: Tesla Model 3
car1.updateModel = "Model S";
console.log(car1.fullName); // Output: Tesla Model S
get fullName()
allows reading the car's full name as a computed property.
set updateModel(newModel)
updates the car model using assignment syntax.