Conteúdo do Curso
Advanced JavaScript Mastery
Advanced JavaScript Mastery
Challenge: Adding Methods to a Class
Task
You're working with a Book
class that represents books in a library. Each book has a title, author, and genre. Your task is to add methods to this class to retrieve information and update the genre.
- Complete the Method Definitions:
- In the existing
Book
class, add a method calledgetInfo
that returns a string in the format:"Title by Author is a Genre book."
; - Add another method named
updateGenre
that takes one parameter,newGenre
, and updates the book'sgenre
property.
- In the existing
- Test the Methods:
- An instance of
Book
namedbook1
has already been created with the values"The Great Gatsby"
," F. Scott Fitzgerald"
, and"Classic"
; - Call
getInfo
to log information about the book; - Use
updateGenre
to change the genre to"Historical Fiction"
; - Call
getInfo
again to confirm the genre update.
- An instance of
class Book { constructor(title, author, genre) { this.title = title; this.author = author; this.genre = genre; } _____() { return `${this._____} by ${this._____} is a ${this._____} book.`; } _____(_____) { this._____ = _____; } } // Instance const book1 = new Book('The Great Gatsby', 'F. Scott Fitzgerald', 'Classic'); // Test the methods console.log(book1._____()); // Expected: The Great Gatsby by F. Scott Fitzgerald is a Classic book. book1._____(_____); // Update genre console.log(book1._____()); // Expected: The Great Gatsby by F. Scott Fitzgerald is a Historical Fiction book.
- Define a method named
getInfo
in theBook
class; - In the
getInfo
method, return a string that usesthis.title
,this.author
, andthis.genre
; - Define a method named
updateGenre
that takes one parameter,newGenre
; - In the
updateGenre
method, setthis.genre
tonewGenre
; - Call
getInfo
onbook1
to log the initial information about the book; - Use
updateGenre
onbook1
to change the genre to"Historical Fiction"
; - Call
getInfo
onbook1
again to confirm the updated genre.
class Book { constructor(title, author, genre) { this.title = title; this.author = author; this.genre = genre; } getInfo() { return `${this.title} by ${this.author} is a ${this.genre} book.`; } updateGenre(newGenre) { this.genre = newGenre; } } // Instance const book1 = new Book('The Great Gatsby', 'F. Scott Fitzgerald', 'Classic'); // Test the methods console.log(book1.getInfo()); // Output: The Great Gatsby by F. Scott Fitzgerald is a Classic book. book1.updateGenre('Historical Fiction'); // Update genre console.log(book1.getInfo()); // Output: The Great Gatsby by F. Scott Fitzgerald is a Historical Fiction book.
Obrigado pelo seu feedback!