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)
JavaScript classes provide a powerful and intuitive way to structure your code using object-oriented principles. By understanding how to use constructors, inheritance, static methods, private fields, and getters/setters, you can write more organized and maintainable code. This tutorial has covered the fundamentals and some advanced features of JavaScript classes, giving you the tools you need to effectively use classes in your projects.