// 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
Let's put everything together by building a simple application using classes. We'll create a Book class and a Library class to manage a collection of books.
class Book {
constructor(title, author, isbn) {
this.title = title;
this.author = author;
this.isbn = isbn;
}
getDetails() {
return `${this.title} by ${this.author} (ISBN: ${this.isbn})`;
}
}
class Library {
constructor() {
this.books = [];
}
addBook(book) {
this.books.push(book);
}
removeBook(isbn) {
this.books = this.books.filter(book => book.isbn !== isbn);
}
listBooks() {
return this.books.map(book => book.getDetails()).join('\n');
}
}
const library = new Library();
const book1 = new Book('The Great Gatsby', 'F. Scott Fitzgerald', '9780743273565');
const book2 = new Book('1984', 'George Orwell', '9780451524935');
library.addBook(book1);
library.addBook(book2);
console.log(library.listBooks());
// Output:
// The Great Gatsby by F. Scott Fitzgerald (ISBN: 9780743273565)
// 1984 by George Orwell (ISBN: 9780451524935)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!