Creating multiple constructor in ES6

谁都会走 提交于 2020-12-31 15:01:57

问题


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

回答1:


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



回答2:


You can also get around this limitation by using ES6 classes with extends.

class Base{
    Foo;
    Bar;
}

class TypeA extends Base {
    constructor(value) {
        this.Foo = value;
    }
}

class TypeB extends Base {
    constructor(value) {
        this.Bar = value;
    }
}



回答3:


Actually, it is indeed possible to create multiple constructors for one prototype. You just have to see that the constructor property of the prototype is not special. Therefore, you can create multiple constructors as follows:

const type = (prototype, constructor) =>
    (constructor.prototype = prototype, constructor);

const book = {
    flipTo(page) {
        this.page = page;
    },
    turnPageForward() {
        this.page++;
    },
    turnPageBackward() {
        this.page--;
    }
};

const EmptyBook = type(book, function EmptyBook() {
    this.constructor = EmptyBook;
    this.ISBN        = "";
    this.title       = "";
    this.author      = "";
    this.genre       = "";
    this.covering    = "";
    this.length      = -1;
    this.page        = 0;
});

const Book = type(book, function Book(title, author, length) {
    this.constructor = Book;
    this.ISBN        = "";
    this.title       = title;
    this.author      = author;
    this.genre       = "";
    this.covering    = "";
    this.length      = length;
    this.page        = 0;
});

Just give the constructors different names. Hope that helps.



来源:https://stackoverflow.com/questions/51580137/creating-multiple-constructor-in-es6

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!