Class - example 1
Defining a class and creating an object.
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.released = year;
}
}
const book1 = new Book('Moby Dick', 'Herman Melville', '1851');
Class - example 2
Adding two methods (getSummary and getAge) to the class, that return a result using template literals.
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.released = year;
}
getSummary (){
return `${this.title} was written by ${this.author} in ${this.released}.`;
}
getAge (){
const years = new Date().getFullYear() - this.released;
return `It was written ${years} years ago.`;
}
}
const book2 = new Book('Pride and Prejudice', 'Jane Austen', '1813');
Class - example 3
Adding a subbclass Magazine.
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.released = year;
}
getSummary (){
return `${this.title} was written by ${this.author} in ${this.released}.`;
}
}
class Magazine extends Book {
constructor(title, author, year, month) {
super(title, author, year);
this.month = month;
}
}
const magazine1 = new Magazine('Now Magazine', 'various authors', '2018', 'June');