HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript Object Constructors

Sometimes we need a blueprint to create many objects of the same type. For example, if you are building a game with thousands of enemies, you need a single template to define what an "Enemy" looks like. In JavaScript, this blueprint is called an Object Constructor.


The Constructor Function

An object constructor is a function. It is considered good practice to name constructor functions with an upper-case first letter (e.g., Person instead of person).

function Person(first, last, age, eye) {
  this.firstName = first;
  this.lastName = last;
  this.age = age;
  this.eyeColor = eye;
}

Creating Instances with 'new'

Objects of the same type are created by calling the constructor function with the new keyword.

const myFather = new Person("John", "Doe", 50, "blue");
const myMother = new Person("Sally", "Rally", 48, "green");

console.log(myFather.age); // 50

The 'this' Keyword

In a constructor function, this does not have a value yet. It is a substitute for the new object. The value of this will become the new object when it is created using the new keyword.


Adding to an Instance

You can add new properties or methods to a single object instance at any time without affecting the other instances or the original constructor.

myFather.nationality = "English"; 
// Only myFather has this property now. myMother does NOT.
Warning: You cannot add a new property to an existing object constructor the same way you add it to an object. To add a new property to a constructor, you must add it to the constructor function definition itself.

Constructor Methods

Your constructor can also define methods that every instance will share:

function Person(first, last) {
  this.firstName = first;
  this.lastName = last;
  this.fullName = function() {
    return this.firstName + " " + this.lastName;
  };
}

Built-in Constructors

JavaScript has built-in constructors for native objects:

  • new Object() — Creates a new Object
  • new String() — Creates a new String (Not recommended)
  • new Number() — Creates a new Number (Not recommended)
  • new Array() — Creates a new Array
  • new Date() — Creates a new Date

Key Points to Remember

  • A Constructor is a blueprint for creating multiple objects
  • Always use the new keyword to create an instance
  • Capitalize the first letter of constructor names (Best practice)
  • The this keyword inside a constructor refers to the new object being created
  • Instance properties can be added individually, but they won't change the blueprint
  • Constructors make your code more organized and reusable