Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ チャレンジ:クラスにメソッドを追加する | JavaScriptクラスと継承の習得
JavaScriptロジックとインタラクション

bookチャレンジ:クラスにメソッドを追加する

メニューを表示するにはスワイプしてください

課題

Book クラスは図書館の本を表します。各本はタイトル、著者、ジャンルを持ちます。このクラスに情報を取得し、ジャンルを更新するメソッドを追加してください。

  1. メソッド定義の完成:
    • 既存の Book クラスに、getInfo というメソッドを追加し、"Title by Author is a Genre book." という形式の文字列を返すようにしてください;
    • もう一つ、updateGenre という名前のメソッドを追加し、1つのパラメータ newGenre を受け取り、本の genre プロパティを更新してください。
  2. メソッドのテスト:
    • Book のインスタンス book1 はすでに "The Great Gatsby", " F. Scott Fitzgerald", "Classic" という値で作成されています;
    • getInfo を呼び出して本の情報をログに出力してください;
    • updateGenre を使ってジャンルを "Historical Fiction" に変更してください;
    • もう一度 getInfo を呼び出してジャンルの更新を確認してください。
1234567891011121314151617181920212223
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.
copy
  • getInfo クラスに Book というメソッドを定義;
  • getInfo メソッド内で this.titlethis.authorthis.genre を使った文字列を返す;
  • updateGenre という1つのパラメータを受け取る newGenre というメソッドを定義;
  • updateGenre メソッド内で this.genrenewGenre に設定;
  • getInfobook1 を呼び出し、本の初期情報をログに出力;
  • updateGenrebook1 を使いジャンルを "Historical Fiction" に変更;
  • getInfo で再度 book1 を呼び出し、ジャンルの更新を確認。
1234567891011121314151617181920212223
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.
copy

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 1.  5

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 1.  5
some-alt