JavaScript

coding learning websites codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

JavaScript Object Constructors


In JavaScript, object constructors are special functions used to create multiple objects with the same structure and properties. Instead of manually creating objects one by one, constructors allow developers to define a blueprint for objects and instantiate new objects efficiently.

Constructors are especially useful when building applications with many similar objects, like users, products, or students. They also introduce the concept of prototypes, enabling shared methods across instances.

1. What is an Object Constructor?

An object constructor is simply a function designed to create objects. By convention, constructor function names start with an uppercase letter.

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}
  • this refers to the new object being created.

  • Each time the constructor is called with new, a new object instance is created.

2. Creating Objects Using Constructor

You create objects using the new keyword:

const person1 = new Person("John", "Doe", 25);
const person2 = new Person("Alice", "Smith", 30);

console.log(person1.firstName); // John
console.log(person2.age);       // 30
  • person1 and person2 are separate instances.

  • Each has its own copy of properties.

3. Adding Methods in Constructors

You can define methods inside constructors.

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;

  this.fullName = function() {
    return this.firstName + " " + this.lastName;
  };
}

const person = new Person("John", "Doe", 25);
console.log(person.fullName()); // John Doe

Note: Methods defined inside the constructor are duplicated for each object, which may use more memory for many instances.

4. Using Prototype for Shared Methods

To save memory, you can add methods to the constructor’s prototype so all instances share the same method:

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

// Add method to prototype
Person.prototype.fullName = function() {
  return this.firstName + " " + this.lastName;
};

const person1 = new Person("John", "Doe", 25);
const person2 = new Person("Alice", "Smith", 30);

console.log(person1.fullName()); // John Doe
console.log(person2.fullName()); // Alice Smith
  • Prototype methods are shared, so memory usage is reduced.

  • This is a key concept in JavaScript object-oriented programming.

5. Constructor with Default Values

You can assign default values to properties in the constructor:

function Person(firstName, lastName, age = 18) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
}

const person = new Person("John", "Doe");
console.log(person.age); // 18
  • Default values ensure that the object has valid properties even if some arguments are missing.

6. Checking Object Type

Objects created with a constructor can be checked using instanceof:

console.log(person instanceof Person); // true
console.log(person instanceof Object); // true
  • instanceof confirms that an object was created from a specific constructor.

7. Constructor Function vs Object Literal

Feature Object Literal Constructor Function
Creation const obj = {} const obj = new Constructor()
Multiple Instances Manual duplication required Easily create many instances
Shared Methods Must define separately Use prototype for shared methods
Dynamic Properties Can assign individually Set via constructor parameters

8. Using Parameters for Dynamic Objects

Constructor functions make objects dynamic by using parameters:

function Product(name, price, quantity) {
  this.name = name;
  this.price = price;
  this.quantity = quantity;

  this.totalCost = function() {
    return this.price * this.quantity;
  };
}

const product1 = new Product("Laptop", 500, 2);
const product2 = new Product("Phone", 300, 5);

console.log(product1.totalCost()); // 1000
console.log(product2.totalCost()); // 1500
  • Each instance has its own properties while sharing the same structure.

9. Notes and Best Practices

  • Constructor function names should start with uppercase letters.

  • Use prototype for methods that do not need to be unique per instance.

  • Always use new when calling a constructor; otherwise, this refers to the global object, causing errors.

  • Constructors are foundational for object-oriented JavaScript and class-based ES6 syntax.

10. Summary of the Tutorial

  • Object constructors are functions used as blueprints to create objects with the same structure.

  • Use the new keyword to instantiate objects.

  • Methods can be defined inside the constructor (per instance) or on prototype (shared).

  • Default values, dynamic parameters, and instanceof checks make constructors flexible and robust.

  • Constructors help avoid repetitive object creation and form the base for modern classes in JavaScript.


Practice Questions

  1. Basic Constructor
    Create a constructor Person with firstName, lastName, and age properties. Instantiate two objects and log their full details.

  2. Method Inside Constructor
    Add a method fullName() inside the Person constructor that returns the full name. Create an object and call this method.

  3. Prototype Method
    Move the fullName() method to the constructor's prototype and demonstrate that both instances can access it.

  4. Default Parameters
    Modify the Person constructor to set a default age of 18 if no age is provided. Create an object without passing age and log it.

  5. Multiple Instances
    Create a Product constructor with name, price, and quantity. Instantiate three different products and log their properties.

  6. Dynamic Method Using Parameters
    Add a method totalCost() in the Product constructor to calculate price * quantity. Call this method for each product.

  7. Checking Constructor
    Use instanceof to check if an object created with Person is actually an instance of Person and Object.

  8. Incorrect Use of new
    Call the Person constructor without new and explain the difference in behavior.

  9. Nested Objects in Constructor
    Create a Student constructor with a nested object marks containing math and science scores. Instantiate a student and log the marks.

  10. Adding Prototype Property
    Add a shared property species = "Homo sapiens" to the Person prototype. Log this property from multiple instances to show it is shared.


JavaScript

online coding class codepractice

JS Basics

JS Variables & Operators

JS Data Types & Conversion

JS Numbers & Math

JS Strings

JS Dates

JS Arrays

JS Control Flow

JS Loops & Iteration

JS Functions

JS Objects

JS Classes & Modules

JS Async Programming

JS Advanced

JS HTML DOM

JS BOM (Browser Object Model)

JS Web APIs

JS AJAX

JS JSON

JS Graphics & Charts

Go Back Top