チャレンジ:クラスにメソッドを追加する
メニューを表示するにはスワイプしてください
課題
Book クラスは図書館の本を表します。各本はタイトル、著者、ジャンルを持ちます。このクラスに情報を取得し、ジャンルを更新するメソッドを追加してください。
- メソッド定義の完成:
- 既存の
Bookクラスに、getInfoというメソッドを追加し、"Title by Author is a Genre book."という形式の文字列を返すようにしてください; - もう一つ、
updateGenreという名前のメソッドを追加し、1つのパラメータnewGenreを受け取り、本のgenreプロパティを更新してください。
- 既存の
- メソッドのテスト:
Bookのインスタンスbook1はすでに"The Great Gatsby"," F. Scott Fitzgerald","Classic"という値で作成されています;getInfoを呼び出して本の情報をログに出力してください;updateGenreを使ってジャンルを"Historical Fiction"に変更してください;- もう一度
getInfoを呼び出してジャンルの更新を確認してください。
1234567891011121314151617181920212223class 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.
getInfoクラスにBookというメソッドを定義;getInfoメソッド内でthis.title、this.author、this.genreを使った文字列を返す;updateGenreという1つのパラメータを受け取るnewGenreというメソッドを定義;updateGenreメソッド内でthis.genreをnewGenreに設定;getInfoでbook1を呼び出し、本の初期情報をログに出力;updateGenreでbook1を使いジャンルを"Historical Fiction"に変更;getInfoで再度book1を呼び出し、ジャンルの更新を確認。
1234567891011121314151617181920212223class 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.
すべて明確でしたか?
フィードバックありがとうございます!
セクション 1. 章 5
AIに質問する
AIに質問する
何でも質問するか、提案された質問の1つを試してチャットを始めてください
セクション 1. 章 5