Back to course

Constructor Functions (Legacy OOP)

JavaScript: The Complete '0 to Hero' Beginner Course

70. Constructor Functions (Legacy OOP)

Before ES6 introduced the class keyword (syntactic sugar), JavaScript used constructor functions to define blueprints for creating multiple objects of the same type.

Defining a Constructor

  1. The function is named starting with a capital letter (a convention).
  2. It takes parameters to set initial properties.
  3. It uses this to assign properties to the newly created object.

javascript function Person(name, age) { this.name = name; this.age = age; this.greet = function() { console.log(Hi, I'm ${this.name}.); }; }

Creating Instances (new Keyword)

To create a new object from this blueprint, we must use the new keyword.

javascript const alice = new Person('Alice', 28); const bob = new Person('Bob', 35);

alice.greet(); // Hi, I'm Alice. console.log(bob.age); // 35

Key: The new keyword automatically creates an empty object, binds this to that object, executes the function, and returns the new object.