Book Class with Composition
Part of the Object Oriented Programming section of Coddy's JavaScript journey — lesson 51 of 56.
Challenge
Create Book Class with Composition
Your task:
- In the file called
Book.jsimport theAuthorclass at the top - Create and export a
Bookclass with:- Private fields:
#title,#author,#isCheckedOut - Constructor that takes
titleandauthor - Two getters:
titleandauthorInfothat returns the author's name
- Private fields:
- In
main.js, add the import forBookclass
How Composition is Applied Here:
Composition means "has-a" relationship. In our Book class:
- Book HAS-AN Author (not "is-an" Author)
- The Book contains an Author instance as one of its components
- The Author exists separately and can be used by multiple Books
- This is composition: building complex objects (Book) from simpler ones (Author)
Try it yourself
import { Author } from './Author.js';
// TODO: Import the Book class
// Tests
const author = new Author('J.K. Rowling');
const book = new Book('Harry Potter', author);
console.log('Book title:', book.title); // Should output: "Book title: Harry Potter"
console.log('Author:', book.authorInfo); // Should output: "Author: J.K. Rowling"All lessons in Object Oriented Programming
1Objects & The this Keyword
Quick Review: ObjectsAdding Methods to ObjectsUnderstanding the this KeywordConstructor FunctionsThe new KeywordRecap Challenge7 Inheritance & The extends Key
InheritanceThe "is-a" RelationshipThe extends KeywordThe super() MethodInheriting Properties&MethodsRecap Challenge2Organizing Code
What are Modules?Exporting with exportImporting with importDefault vs. Named Exports8Organizing OOP Code
Organize Classes into Modules11Project: A Shape Renderer
Setup: Shape Class & ExportCircle Class Inheritance9Static Methods & Properties
Class-Level vs. Instance-LevelStatic PropertiesStatic Utility MethodsRecap challenge