// 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
Related Posts
More content you might like
Tutorial
javascript
Understanding JavaScript Classes
As of ECMAScript 2022, JavaScript supports private fields and methods, which are not accessible outside of the class definition. This is done by prefixing the field or method name with #.
class Counter {
#count = 0;
increment() {
this.#count++;
console.log(this.#count);
}
getCount() {
return this.#count;
}
}
const counter = new Counter();
counter.increment(); // Output: 1
console.log(counter.getCount()); // Output: 1
console.log(counter.#count); // Error: Private field '#count' must be declared in an enclosing classSep 02, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!