javascriptecmascript-6es6-class

Can constructors be overloaded in ES6 classes?


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 (){}
}

Solution

  • 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;
            }
        }