0
0
Javascriptprogramming~5 mins

Constructor functions in Javascript

Choose your learning style9 modes available
Introduction

Constructor functions help you create many similar objects easily. They set up new objects with properties and values.

When you want to create many objects with the same structure, like many users or cars.
When you want to organize your code to make object creation clear and reusable.
When you want each object to have its own properties but share the same setup steps.
When you want to add methods to objects created from the same constructor.
When you want to keep your code clean and avoid repeating the same object setup.
Syntax
Javascript
function ConstructorName(parameter1, parameter2) {
  this.property1 = parameter1;
  this.property2 = parameter2;
  // more properties or methods
}

The function name usually starts with a capital letter to show it is a constructor.

Use the new keyword to create a new object from the constructor.

Examples
This constructor creates a Person with a name and age.
Javascript
function Person(name, age) {
  this.name = name;
  this.age = age;
}
Creates two Person objects with different names and ages.
Javascript
const person1 = new Person('Alice', 30);
const person2 = new Person('Bob', 25);
This constructor adds a method honk to each Car object.
Javascript
function Car(make, model) {
  this.make = make;
  this.model = model;
  this.honk = function() {
    console.log('Beep beep!');
  };
}
Sample Program

This program creates two dogs with names and breeds. Each dog can bark, printing a message with its name.

Javascript
function Dog(name, breed) {
  this.name = name;
  this.breed = breed;
  this.bark = function() {
    console.log(this.name + ' says Woof!');
  };
}

const dog1 = new Dog('Buddy', 'Golden Retriever');
const dog2 = new Dog('Max', 'Beagle');

dog1.bark();
dog2.bark();
OutputSuccess
Important Notes

Always use new when calling a constructor function to create a new object.

Inside the constructor, this refers to the new object being created.

Methods defined inside the constructor are created for each object separately. To save memory, use prototypes for shared methods.

Summary

Constructor functions help create many similar objects easily.

Use new to make a new object from a constructor.

this inside the constructor means the new object being made.