0
0
Javascriptprogramming~5 mins

Constructors in classes in Javascript

Choose your learning style9 modes available
Introduction

A constructor is a special function inside a class that runs automatically when you create a new object. It helps set up the object with initial values.

When you want to create a new object with specific starting information.
When you need to set up properties for an object right away.
When you want to make sure every object of a class starts with some default values.
When you want to pass data to an object as you create it.
Syntax
Javascript
class ClassName {
  constructor(parameters) {
    // code to set up the object
  }
}

The constructor method is named exactly constructor.

It runs automatically when you use new ClassName().

Examples
This constructor sets the name property when creating a new Person.
Javascript
class Person {
  constructor(name) {
    this.name = name;
  }
}
This constructor sets two properties: make and model.
Javascript
class Car {
  constructor(make, model) {
    this.make = make;
    this.model = model;
  }
}
This constructor just prints a message when an object is created.
Javascript
class Empty {
  constructor() {
    console.log('A new object was created');
  }
}
Sample Program

This program creates a Dog object with a name and breed. Then it calls the bark method to print a message.

Javascript
class Dog {
  constructor(name, breed) {
    this.name = name;
    this.breed = breed;
  }

  bark() {
    return `${this.name} says Woof!`;
  }
}

const myDog = new Dog('Buddy', 'Golden Retriever');
console.log(myDog.bark());
OutputSuccess
Important Notes

You can only have one constructor method in a class.

If you don't write a constructor, JavaScript adds an empty one automatically.

Use this to set properties inside the constructor.

Summary

Constructors set up new objects with starting values.

They run automatically when you create an object with new.

Use this inside constructors to assign properties.