#1 India's Top IT Training Institute
×

About Uncodemy

Know more about who we are and what we stand for.

About Us

About Us

Discover our mission to equip individuals with essential IT skills and industry expertise.

Read More →
UnCodeMy Gallery

UnCodeMy Gallery

Explore highlights from our IT training sessions and success stories.

Read More →
Mentors

Mentors

Meet the industry experts who train and guide you through your course.

Read More →
Free Resources

Free Resources

Free tutorials, interview questions, tools and calculators to help you learn.

Explore →
×

Free Resources

Learn, practice and plan your career — bilkul free.

Tutorials

Tutorials

Step-by-step written tutorials to learn any technology at your own pace.

Read More →
Free Counselling

Free Counselling

Book a free video counselling session and pick the right course for you.

Read More →
Online Compiler

Online Compiler

Write, run and test your code online — no setup required.

Read More →
JavaScript Fundamentals

Constructor function

A constructor function is a regular function designed to be called with the new keyword to create many objects with the same shape. Instead of writing an object literal again and again for each user, product or bank account, you write one function that sets up the properties, and new builds a fresh object every time. It is the pattern JavaScript used for object creation before class syntax arrived, and classes still work this way underneath.

Writing and calling one

By convention, constructor names start with a capital letter to signal that they need new.

function BankAccount(owner, balance = 0) {
  this.owner = owner;
  this.balance = balance;
}

BankAccount.prototype.deposit = function (amount) {
  this.balance += amount;
  return this.balance;
};

const a = new BankAccount('Asha', 500);
const b = new BankAccount('Ravi');

a.deposit(250);
console.log(a.balance);                    // 750
console.log(b.balance);                    // 0
console.log(a instanceof BankAccount);     // true
console.log(a.deposit === b.deposit);      // true: one shared method

What new does behind the scenes

When you write new BankAccount('Asha', 500), JavaScript performs four steps:

  1. Creates a brand new empty object.
  2. Links that object's prototype to BankAccount.prototype, so it can use methods placed there.
  3. Calls the function with this pointing at the new object, so this.owner = owner adds a property to it.
  4. Returns the new object automatically, unless the function explicitly returns a different object.

That is why you never write return this in a constructor. It happens for you.

Where methods should live

You could put a method inside the constructor, like this.deposit = function () {...}. It works, but every object then gets its own copy of the function. With a thousand accounts, that is a thousand identical functions in memory. Adding the method to BankAccount.prototype instead means all objects share one function, as the a.deposit === b.deposit check shows. Properties that differ per object, like owner and balance, belong on this; behaviour that is the same for all of them belongs on the prototype. The next lesson explores prototypes in detail.

Forgetting new is a silent bug

If you call BankAccount('Asha', 500) without new, no object is created and the function returns undefined. Worse, in non-strict code this refers to the global object, so you accidentally create global variables called owner and balance. In strict mode, which modules and classes use by default, this is undefined and the line throws a TypeError instead, which at least makes the problem visible.

You can protect a constructor by checking new.target, which is undefined when the function was called without new:

if (!new.target) throw new Error('Use new BankAccount()');

Also avoid arrow functions as constructors. Arrow functions have no this of their own and no prototype, so calling one with new throws an error.

How this relates to class syntax

A class is mostly a cleaner way of writing the same thing. class BankAccount { constructor(owner, balance = 0) {...} deposit(amount) {...} } creates a constructor function and puts deposit on its prototype. Classes also refuse to run without new. Understanding constructor functions explains what classes are actually doing, and helps when you read older code or libraries.

Key ideas

  • Capitalise the name and always call it with new.
  • Set per-object data on this and shared methods on the prototype.
  • new creates, links, runs and returns the object for you.

Ready to master real-world web development?

Learn HTML, CSS3, Bootstrap and JavaScript hands-on with mentor-led sessions.

Explore Course