JavaScript Constructor Functions

Constructor Functions

1. A function which is used to create an object is known as constructor function.

2. A constructor function behaves like blueprint or template for object, and there is no need to write code again and again.

3. It helps us to create multiple objects of same type.

4. Syntax: function identifier(parameter,...){ }

5. If the function is designed to use as a constructor, the name of function should be UpperCamelCase.

6. The list of parameters provided to the function will be treated as keys/properties of the object.

7. The arguments passed when function is called will be values of the object.

8. We can copy the values into the keys of the object from parameters using this keyword.

9. We can create an object using the constructor function with the help of new keyword.

10. To create constructor function we will not use arrow function because they don't have 'this' keyword.

11. Syntax: let variable = new function_name(arguments)

Constructor Function Example

function Car(model, color, engine) {
  this.model = model;
  this.color = color;
  this.engine = engine;
}

let car1 = new Car(1021, "red", "V8");
console.log(car1);
// Output: { model: 1021, color: "red", engine: "V8" }
Key Points:
  • The new keyword creates a new empty object
  • The constructor function is called with the specified arguments
  • this inside the function refers to the new object
  • The function automatically returns the new object

Creating Multiple Objects

Constructor functions allow us to create multiple similar objects easily:

function Car(model, color, engine) {
  this.model = model;
  this.color = color;
  this.engine = engine;
}

let car1 = new Car(1021, "red", "V8");
let car2 = new Car(2022, "blue", "V6");
let car3 = new Car(2023, "black", "Electric");

console.log(car1);
// { model: 1021, color: "red", engine: "V8" }
console.log(car2);
// { model: 2022, color: "blue", engine: "V6" }
console.log(car3);
// { model: 2023, color: "black", engine: "Electric" }

Adding Methods to Constructor Functions

We can also add methods to objects created with constructor functions:

function Car(model, color, engine) {
  this.model = model;
  this.color = color;
  this.engine = engine;
  
  this.start = function() {
    console.log(`${this.model} with ${this.engine} engine is starting!`);
  };
  
  this.describe = function() {
    console.log(`This is a ${this.color} car model ${this.model}`);
  };
}

let myCar = new Car(1021, "red", "V8");
myCar.start();      // "1021 with V8 engine is starting!"
myCar.describe();   // "This is a red car model 1021"