Class Fields and Methods
Class fields and methods provide a more convenient way to define instance variables and methods directly within the class declaration.
class Circle {
radius = 0;
constructor(radius) {
this.radius = radius;
}
get area() {
return Math.PI * this.radius ** 2;
}
static circumference(radius) {
return 2 * Math.PI * radius;
}
}
const circle = new Circle(5);
console.log(circle.area); // Output: 78.53981633974483
console.log(Circle.circumference(5)); // Output: 31.41592653589793
In the example above, the Circle class has a class field radius and a getter method area that calculates the area of the circle. The circumference method is declared as a static method, which can be invoked directly on the class itself.
No comments:
Post a Comment