// Class definition for Person
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
// Method to generate a greeting
greet() {
return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
}
}
// Usage of the Person class
const person = new Person('John', 30);
const greeting = person.greet();
JavaScript Class with Constructor and Method
javascript
Continue Reading
Discover more amazing content handpicked just for you
Tutorial
javascript
Understanding JavaScript Classes
Getters and setters allow you to define methods that are executed when a property is accessed or modified. This can be useful for validating data or performing side effects.
class Rectangle {
constructor(width, height) {
this.width = width;
this.height = height;
}
get area() {
return this.width * this.height;
}
set width(value) {
if (value <= 0) throw new Error("Width must be positive");
this._width = value;
}
get width() {
return this._width;
}
}
const rect = new Rectangle(10, 5);
console.log(rect.area); // Output: 50
rect.width = 15;
console.log(rect.area); // Output: 75
Sep 02, 2024
Discussion 0
Please sign in to join the discussion.
No comments yet. Start the discussion!