// 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
class Animal {
constructor(type, name) {
this.type = type;
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
const dog = new Animal('Dog', 'Buddy');
dog.speak(); // Output: Buddy makes a noise.Inheritance allows a class to extend another class, inheriting its properties and methods while adding new ones or overriding existing ones.
Sep 02, 2024
Read More Code
python
Class with Method
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f'Hello, my name is {self.name} and I am {self.age} years old.'
# Create an instance of Person
person = Person('Alice', 25)
# Call the greet method and store the result in 'greeting'
greeting = person.greet()Jan 26, 2024
Read MoreDiscussion 0
Please sign in to join the discussion.
No comments yet. Be the first to share your thoughts!