ES6-Class

JavaScript ES6 finally brings a true object-oriented class design to JavaScript, complete with the 'class' and 'constructor' keywords. ES6 also brought with it an easy way to inherit from one class to another using the 'extends' keywords. Now, JavaScript behaves much more similarly to other object-oriented languages.

by manoj_antony32

JavaScript

/* ES5 format class creation */
function _instanceof(instance, Constructor) {
console.log(Constructor[Symbol.hasInstance])
    if (Constructor != null && typeof Symbol !== "undefined" && Constructor[Symbol.hasInstance]) {
        return !!Constructor[Symbol.hasInstance](instance);
    } else {
        return instance instanceof Constructor;
    }
}
function _classCallCheck(instance, Constructor) {
    if (!_instanceof(instance, Constructor)) {
        throw new TypeError("Cannot call a class as a function");
    }
}
var Car = function Car(brand) {
    _classCallCheck(this, Car);
    this.carname = brand;
};
var mycar = new Car("Ford");
console.log(mycar)

/* ES6 format class */
class Book {
    constructor(title, author, pages) {
        this.title = title;
        this.author = author;
        this.pages = pages;
    }

    getPageCount() {
        return this.pages;
    }

    getAuthor() {
        return this.author;
    }

    getTitle() {
        return this.title;
    }
}
class Novel extends Book {
    constructor(title, author, pages, genre) {
        super(title, author, pages);
        this.genre = genre;
    }

    getGenre() {
        return this.genre;
    }
}
let book = new Novel('The Hobbit', 'J.R.R. Tolkien', 310, 'Fantasy');
console.log(book.getAuthor());