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.
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 Book
class definition and then create a Book
object 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.
xxxxxxxxxx
class Book {
constructor(title, author, ISBN, numberOfPages, publicationYear) {
this.title = title;
this.author = author;
this.ISBN = ISBN;
this.numberOfPages = numberOfPages;
this.publicationYear = publicationYear;
}
get title() {
return this._title
}
set title(value) {
this._title = value
}
paperbackOrHardcover() {
if (this.numberOfPages > 500) {
return 'hardcover'
} else {
return 'paperback'
}
}
}