Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating multiple constructor in ES6

In ES5 it was possible to create multiple constructors for a class while keeping common parts to both using prototypes, as shown below

function Book() {
    //just creates an empty book.
}


function Book(title, length, author) {
    this.title = title;
    this.Length = length;
    this.author = author;
}

Book.prototype = {
    ISBN: "",
    Length: -1,
    genre: "",
    covering: "",
    author: "",
    currentPage: 0,
    title: "",

    flipTo: function FlipToAPage(pNum) {
        this.currentPage = pNum;
    },

    turnPageForward: function turnForward() {
        this.flipTo(this.currentPage++);
    },

    turnPageBackward: function turnBackward() {
        this.flipTo(this.currentPage--);
    }
};

var books = new Array(new Book(), new Book("First Edition", 350, "Random"));

I want to achieve the same result using ES6 class and constructor syntax

class Book{
    constructore (){}
}
like image 253
Varun Sukheja Avatar asked Dec 11 '22 05:12

Varun Sukheja


1 Answers

Function/constructor overloading is not supported in ECMAScript. You can use the arguments object to do so if you want to still hack it.

constructor(title, length, author) {
        if(!arguments.length) {
            // empty book
        }
        else {
            this.title = title;
            this.Length = length;
            this.author = author;
        }
    }
like image 82
Saransh Kataria Avatar answered Dec 14 '22 22:12

Saransh Kataria