Mark As Completed Discussion

Classes and Objects in JavaScript

We can define classes in JavaScript through the class keyword. Since JavaScript is a dynamic programming language, the methods and functions in a class can refer to and set values of attributes (called properties in JavaScript) not even declared. For example, the definition of the Book class and how to create a new Book object in JavaScript is shown below.

JAVASCRIPT
1class Book {
2	constructor(title, author, ISBN, numberOfPages, publicationYear) {
3		this.title = title;
4		this.author = author;
5		this.ISBN = ISBN;
6		this.numberOfPages = numberOfPages;
7		this.publicationYear = publicationYear;
8	}
9	paperbackOrHardcover() {
10		if this.numberOfPages > 500 {
11			return 'hardcover'
12		} else {
13			return 'paperback'
14		}
15	}
16}
17let myBook = new Book(‘Life of Pi’, ‘Yann Martel’, 9780156027328, 352, 2001)
18console.log(myBook.paperbackOrHardcover())
19// prints 'paperback' for the myBook object

Here, we create the Bookclass definition and then create a Bookobject instance with the new keyword. Then, we print the result of paperbackOrHardcover()method to the console.

Note: Always use the new keyword to create a new object instance.

Methods that retrieve or set an attribute value can be designated with the get and set keywords. This avoids confusion since the method name is the same as the attribute name.

Notice these methods reference the property value through this._title instead of the regular this.title, as shown below. This is to avoid confusion since the method name is the same as the attribute name.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment