Sitemap

Young Coder

Insights into the .NET stack. Thought pieces about the craft of software development. Real advice for teaching kids to code. And a shot of humor.

Supporting Multiple Constructors in JavaScript

3 patterns for object creation

4 min readSep 26, 2021

--

Image

If your background is in a traditional object-oriented programming language, you might be thrown by the wild and sometimes lawless world of JavaScript. There are objects here — but they’re really prototypes, and all the syntax about classes and inheritance was bolted on in relatively recent versions. Some OO concepts still don’t fit. Others force you to adapt.

In a traditional OO language, multiple constructors are nothing special. You simply add overloaded versions of the constructor function, much as you add overloaded versions to any method. But JavaScript doesn’t enforce strict argument lists and doesn’t have a concept of function overloading. So what’s the JavaScript way to support multiple constructors?

You have a few choices.

1. Optional parameters with defaults

Every JavaScript class has exactly one constructor. If you want to give yourself some flexibility with object creation, the quick-and-dirty solution is simple. Just add all the parameters you could possibly need to the one-and-only constructor:

class Person {
constructor(firstName, lastName, dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
}
}

Now you have plenty of options for creating Person objects without supplying every argument:

const newPerson = new Person('Luke', 'Takei',
new Date(1990, 5, 22));
const noDatePerson = new Person('Luke', 'Takei');
const firstNamePerson = new Person('Luke');
const noDataPerson = new Person();

This looseness isn’t without some problems. It’s not always easy to tell if a value has been supplied by the calling code. If it makes sense, you should explicitly set default values that the class can use:

class Shape{
constructor(shapeName='rectangle', height=1, width=1) {
this.shapeName= shapeName;
this.height = height;
this.width = width;
}
}

Now when you create a Shape object, you can pick and choose which values you supply.

// Create a 1x1 circle
const circle = new Shape('circle');

--

--

Young Coder
Young Coder

Published in Young Coder

Insights into the .NET stack. Thought pieces about the craft of software development. Real advice for teaching kids to code. And a shot of humor.

Matthew MacDonald
Matthew MacDonald

Written by Matthew MacDonald

Teacher, coder, long-ago Microsoft MVP. Author of heavy books. Join Young Coder for a creative take on science and technology. Queries: matthew@prosetech.com

No responses yet