Challenge - Object management
Build a library book app with objects, properties and methods.
Library book challenge
In this challenge you will design a library book object. The book carries title, author, pages and readCount properties.
You will add a read() method to the object. Each time it is called, it should increment this.readCount by one and return a string that includes the book's title.
The this keyword refers to the object the method was called on. So when book.read() runs, this is the book object. Inside the method, this.readCount and this.title reach the correct values.
Method shorthand and this
The short way to define a method inside an object is the method shorthand: you write read() { ... }, not read: function() { ... }.
Inside the method, this refers to the object that called it. In book.read(), this is book. You can increment the counter with this.readCount++.
Be careful: arrow functions bind this differently. For this task you must use the classic method shorthand; do not use an arrow function.
Exercise Define the book object
Define an object with const book. Add title, author and pages properties; set readCount to 0. Add a read() method using method shorthand: it should increment this.readCount with ++ and return a template literal that includes this.title.
Show example solution
0. Write a read() { ... } method; increment with this.readCount++ and return `${this.title} read.`.
Example solution:
const book = {
title: "One Hundred Years of Solitude",
author: "Gabriel Garcia Marquez",
pages: 417,
readCount: 0,
read() {
this.readCount++;
return `${this.title} read.`;
}
};
Test yourself
-
Match the parts of the book object
- title
- Book name
- author
- Book writer
- pages
- Number of pages
- read
- Read method
-
What does this refer to inside a method called as book.read()?
const book = { readCount: 0, read() { this.readCount++; } }; book.read();- The global window object
- The read function itself
- The book object
- The undefined value
Show answer
The book object — Correct. With method shorthand, this binds to the object that called the method, namely book.