- Learning JavaScript Data Structures and Algorithms
- Loiane Groner
- 189字
- 2021-08-27 18:41:10
Object-oriented programming with classes
ES2015 also introduced a cleaner way of declaring classes. You learned that we can declare a class named Book in the object-oriented programming section this way:
function Book(title, pages, isbn) { // {1} this.title = title; this.pages = pages; this.isbn = isbn; } Book.prototype.printTitle = function() { console.log(this.title); };
With ES2015, we can simplify the syntax and use the following code:
class Book { // {2} constructor(title, pages, isbn) { this.title = title; this.pages = pages; this.isbn = isbn; } printIsbn() { console.log(this.isbn); } }
We can simply use the keyword class and declare a class with a constructor function and other functions as well—for example, the printIsbn function. ES2015 classes are syntactical sugar over the prototype-based syntax. The code for the Book class declared in line {1} has the same behavior and output as the code declared in line {2}:
let book = new Book('title', 'pag', 'isbn'); console.log(book.title); // outputs the book title book.title = 'new title'; // update the value of the book title console.log(book.title); // outputs the book title
The preceding example can be executed at https://goo.gl/UhK1n4.