- Home
- /
- Tutorials
- /
- JavaScript Tutorial
- /
- JavaScript Class Getters and Setters
JavaScript Classes
JavaScript Class Getters and Setters
Class getters and setters let a method be used like a plain property.
The syntax is the same as in an object literal, but it matters more here.
Paired with a private field, a getter is how a class controls access to its data.
Example
Example
javascript
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
}
console.log(new Rectangle(4, 5).area);