Saturday, June 1, 2024
173
rated 0 times [  174] [ 1]  / answers: 1 / hits: 7710  / 6 Years ago, sun, july 29, 2018, 12:00:00

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

More From » ecmascript-6

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

[#12117] Friday, July 27, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
matteo

Total Points: 81
Total Questions: 100
Total Answers: 96

Location: Honduras
Member since Sat, Jul 24, 2021
3 Years ago
matteo questions
Tue, Mar 8, 22, 00:00, 2 Years ago
Sun, May 31, 20, 00:00, 4 Years ago
Thu, Mar 12, 20, 00:00, 4 Years ago
Tue, Jan 22, 19, 00:00, 5 Years ago
Wed, Sep 12, 18, 00:00, 6 Years ago
;