JS Object Constructors

JavaScript Object Constructors: A Beginner's Guide

Whenever you need to create multiple objects with the exact same structure, creating a new object literal every single time is repetitive and hard to maintain. For example, if you are managing a car inventory, you need a blueprint to create many different car objects efficiently.

In JavaScript, an Object Constructor is a function that serves as a blueprint (or template) for creating objects.

A constructor is invoked using the new keyword. Its main purpose is to create a new object, initialize it, and set values for its properties. The primary benefit of using object constructors is code reusability.


1. Syntax of an Object Constructor

By convention, constructor functions always start with a Capital Letter so developers can easily identify them.

function ConstructorName(param1, param2) {
   this.property1 = param1;
   this.property1 = param2;
}

const myObject = new ConstructorName(arg1, arg2);


2. Creating an Object Using a Constructor

In the example below, we create a basic Tree() constructor function. In the function body, we initialize the name and age properties. After that, we use the new keyword to create an object from the Tree() constructor.

Basic Constructor Example

function Tree() {
  this.name = "Palm";
  this.age = 5;
}

// Creating an instance of Tree const tree1 = new Tree();

console.log("name = " + tree1.name + ", age = " + tree1.age);


3. Constructor Functions with Parameters

Constructors become truly powerful when you pass parameters into them. In the example below, the Bike() function takes three parameters.

We can now easily create bike1 and bike2 objects with completely different values using the exact same Bike() constructor blueprint!

Constructor with Parameters

function Bike(name, speed, gear) {
  this.name = name;
  this.speed = speed;
  this.gear = gear;
}

const bike1 = new Bike("Honda", 100, 4); const bike2 = new Bike("Yamaha", 200, 6);

console.log(bike1); console.log(bike2);


4. Adding Properties or Methods to a Constructor

You have already learned how to add a property or method to a standard object using dot notation (e.g., obj.newProperty = "value").

However, you cannot add a new property directly to an object constructor from the outside. Doing Bike.color = "Red" will not add the color property to your objects.

To add properties or methods to all objects created by a constructor, you must add them directly inside the constructor function body:

Adding Methods Inside a Constructor

function HouseAddress(no, street, city) {
  // Adding properties
  this.houseNo = no;
  this.street = street;
  this.city = city;
  

// Adding a method this.getFullAddress = function () { return this.houseNo + ", " + this.street + ", " + this.city; }; }

const house = new HouseAddress(20, "Cooper Square", "New York"); console.log(house.getFullAddress());

Note: If you add a property directly to an instance later (like house.color = "White";), it will ONLY be added to that single house object, not to any other houses created by the HouseAddress constructor.


5. Using the JavaScript Object Prototype

What if you want to add a new method to a constructor after it has already been defined? You can do this using the Prototype.

In JavaScript, every object constructor has a prototype property by default. You can use it to attach new properties and methods that will immediately become available to all instances created from that constructor!

Syntax:

ConstructorName.prototype.methodName = function() { ... };

Adding Methods via Prototype

function Bike(name, speed, gear) {
  this.name = name;
  this.speed = speed;
  this.gear = gear;
}

// Adding a method using Prototype Bike.prototype.getBikeDetails = function () { return this.name + " goes " + this.speed + "km/h on gear " + this.gear; };

const bike1 = new Bike("Honda", 100, 4); const bike2 = new Bike("Yamaha", 200, 6);

// Both bikes now have access to getBikeDetails()! console.log(bike1.getBikeDetails()); console.log(bike2.getBikeDetails());

(Note: When you log the bike1 object using console.log or JSON.stringify, you won't directly see the getBikeDetails method attached to it because it is inherited from the prototype, keeping your objects lightweight!)


6. Built-in Object Constructors

JavaScript comes with several built-in constructors for its native data types.

Constructor Description Example
Array Creates an array object. new Array("Apple", "Banana")
String Creates a string object. new String("Hello")
Number Creates a number object. new Number(92)
Boolean Creates a boolean object. new Boolean(true)
Set Creates a new set collection. new Set()
Map Creates a new map collection. new Map()
Object Creates a generic object. new Object()
Function Creates a new function object. new Function("x", "return x * x;")
Date Creates an instance of a Date object. new Date()
RegExp Creates a regular expression object. new RegExp("\\d+")
Error Creates a new error object. new Error("Something went wrong.")
Symbol Creates a unique symbol. (Does not use new) Symbol("description")

Best Practice: While you can use constructors like new String() or new Number(), it is highly recommended to use primitive literal expressions (e.g., let x = "Hello";) instead. Using built-in primitive constructors slows down execution speed and can lead to unexpected buggy behavior when comparing values.


Exercise

?

Which keyword is required to properly create a new instance of an object from a constructor function?