Mimicking OOP

Object Constructors

Suppose we want to create multiple “account” objects. In class-based OOP, a class is what lets us do that. We instantiate the class with the new keyword, and we get an object back. JavaScript did not have classes as blueprints to instantiate objects. But from the beginning, it did let developers use constructor functions to create objects. Here is an example:

function Account() {
  this.balance = 0;
  this.deposit = function (amount) {
    this.balance += amount;
  };
}

// Create any number of accounts
const acc1 = new Account();
const acc2 = new Account();

acc1.deposit(10);
acc2.deposit(20);

console.log(acc1); // {"balance":10}
console.log(acc2); // {"balance":20}

We usually capitalize the name of a constructor function. That is only a convention. The two parts that matter are calling the function with the new keyword and using the this keyword inside the function to build the object.

This is close to how object creation works in class-based languages such as Java and C++. A class constructor in those languages does the same job as a constructor function here. For example, we can pass arguments to set up the object’s properties.

function Account(balance) {
  this.balance = balance;
  this.deposit = function (amount) {
    this.balance += amount;
  };
}

// Create any number of accounts
const acc1 = new Account(10);
const acc2 = new Account(20);

console.log(acc1); // {"balance":10}
console.log(acc2); // {"balance":20}

Most functions in JavaScript can be used as constructor functions with the new keyword. (Arrow functions are an exception. They cannot be used with new.) JavaScript also has built-in constructor functions:

new Object(); // Creates a new Object
new Array(); // Creates a new Array
new Map(); // Creates a new Map
new Set(); // Creates a new Set
new Date(); // Creates a new Date
new RegExp(); // Creates a new RegExp
new Function(); // Creates a new Function