Patterns for Multiple JavaScript Constructors
- Parameter Sniffing in JavaScript
- Static Methods in JavaScript
- JavaScript Methods in Functions
- Optional Parameters With Defaults in JavaScript
- Single Object Literal in JavaScript
This article will teach you five different patterns for multiple constructors in JavaScript. The following are the multiple constructors’ patterns.
- Parameter sniffing
- Static methods
- Methods in functions
- Optional parameters with defaults
- Single object literal
Parameter Sniffing in JavaScript
Parameter sniffing is about checking the parameter type and creating a constructor for it. If the parameter is a string, you can use the typeof
operator to determine a string.
You can also specify how a constructor will work for a string and do this for other data types.
Code:
function ConstructWithParam(a) {
if (typeof (a) === 'string') {
this.name = 'You supplied a string';
console.log(this.name);
}
if (typeof (a) === 'number') {
this.name = 'You supplied a number';
console.log('You supplied a number');
}
}
let aNumber = new ConstructWithParam(2);
let aString = new ConstructWithParam('Hello');
console.log(aNumber, aString);
Output:
You supplied a number
You supplied a string
Object { name: "You supplied a number" }
Object { name: "You supplied a string" }
In this case, we’ve logged a message to the console.
Static Methods in JavaScript
You can create static methods that return a new class instance, resulting in multiple constructors. You’ll find this approach useful if you want to be strict about instantiating a class or creating objects with complex combinations.
Code:
class multiConstructor {
constructor(w = '', x = '', y = '', z = '') {
this.w = w;
this.x = x;
this.y = y;
this.z = z;
}
static WandXInstance(w, x) {
return new multiConstructor(w, x, '', '');
}
static YandZInstance(y, z) {
return new multiConstructor('', '', y, z)
}
}
let objectWithDefaultConstructor = new multiConstructor('Alpha', 'Bravo');
let objectFromStaticMethod = multiConstructor.YandZInstance('Charlie', 'Delta');
console.log(objectWithDefaultConstructor);
console.log(objectFromStaticMethod);
Output:
Object { w: "Alpha", x: "Bravo", y: "", z: "" }
Object { w: "", x: "", y: "Charlie", z: "Delta" }
These static methods use different class parameters and return a new instance of that class. You are not limited to creating one type of instance with the default constructor.
JavaScript Methods in Functions
Functions can have properties and methods like every other object. Using methods in the function, you can use the methods to serve the purpose of a constructor.
Therefore, you can create objects with alternative arguments. Though the methods are not an exact constructor, it’s all you need in this scenario.
We’ve defined a function in the following code and added a method to it.
Code:
function MultiCon(multicon) {
this.multicon = multicon;
}
MultiCon.prototype = {
multiCon: null,
}
MultiCon.someComponents =
function(a, b) {
var ab = a + b;
return new MultiCon(ab);
}
var x = MultiCon.someComponents('Mada', 'Gascar');
var y = new MultiCon('Mada');
console.log(x, y);
Output:
Object { multicon: "MadaGascar" }
Object { multicon: "Mada" }
In this example, calling the function with the new
keyword or using the added method yields the same result.
Optional Parameters With Defaults in JavaScript
You can add optional parameters to a class constructor, and these parameters can have default values. We won’t have to specify all the arguments when creating a class instance.
Code:
class Employee {
constructor(first_name, last_name, date_of_birth) {
this.first_name = first_name;
this.last_name = last_name;
this.date_of_birth = date_of_birth;
}
}
const newEmployee =
new Employee('Scarlett', 'Johannsen', new Date(1989, 2, 20));
const newEmployee_noDOB = new Employee('Magaret', 'Tatcher');
const newEmployee_firstNameOnly = new Employee('John');
const newEmployee_noBioData = new Employee();
console.log(newEmployee);
console.log(newEmployee_noDOB);
console.log(newEmployee_firstNameOnly);
console.log(newEmployee_noBioData);
Output:
Object { first_name: "Scarlett", last_name: "Johannsen", date_of_birth: Date Mon Mar 20 1989 00:00:00
Object { first_name: "Magaret", last_name: "Tatcher", date_of_birth: undefined }
Object { first_name: "John", last_name: undefined, date_of_birth: undefined }
Object { first_name: undefined, last_name: undefined, date_of_birth: undefined }
However, you cannot know if the class received a value or values from the calling code. You can notice this from the previous output, where we have a series of undefined
values.
You can set default values that the class can use when it receives no arguments to take care of this.
Code:
class Employee {
constructor(
first_name = 'New Employee', last_name = 'New Employee',
date_of_birth = '1970-01-01') {
this.first_name = first_name;
this.last_name = last_name;
this.date_of_birth = date_of_birth;
}
}
const newEmployee_noBioData = new Employee();
const newEmployee_firstNameOnly = new Employee('John');
console.log(newEmployee_noBioData);
console.log(newEmployee_firstNameOnly);
Output:
Object { first_name: "New Employee", last_name: "New Employee", date_of_birth: "1970-01-01" }
Object { first_name: "John", last_name: "New Employee", date_of_birth: "1970-01-01" }
When creating objects from the class, you can use undefined
in place of a default value. The undefined
keyword tells the class to use the default value in the class definition.
class Employee {
constructor(
first_name = 'New Employee', last_name = 'New Employee',
date_of_birth = '1970-01-01') {
this.first_name = first_name;
this.last_name = last_name;
this.date_of_birth = date_of_birth;
}
}
const newEmployee_firstNameOnly = new Employee(undefined, 'Martinez');
console.log(newEmployee_firstNameOnly);
Output:
Object { first_name: "New Employee", last_name: "Martinez", date_of_birth: "1970-01-01" }
Single Object Literal in JavaScript
Putting optional parameters into a single object will be useful if you have many optional flags that the calling code might not use. There is no type checking or linting for the object properties, so you can’t tell if there is a mistake in a property name.
Code:
class System {
constructor(hardware_maker, chipset_maker, operatingSystem = {}) {
this.hardware_maker = hardware_maker;
this.chipset_maker = chipset_maker;
this.operatingSystem = operatingSystem;
}
}
const newSystem = new System('Intel', 'Nvidia', {
'OS Version': 'Windows 7',
'Service Pack Update': '2009-03-05',
'Windows Update Last Checked': '2009-03-05'
});
const newSystem2 = new System('AMD', 'GeoFeorce');
console.log(newSystem);
console.log(newSystem2);
Output:
Object { hardware_maker: "Intel", chipset_maker: "Nvidia", operatingSystem: { "OS Version": "Windows 7", "Service Pack Update": "2009-03-05", "Windows Update Last Checked": "2009-03-05" } }
Object { hardware_maker: "AMD", chipset_maker: "GeoFeorce", operatingSystem: {} }
In the above code, we’ve set up an object. The object will take the Operating System details inside the operatingSystem
object.
Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.
LinkedIn