DEV Community

Randy Rivera
Randy Rivera

Posted on

Define a Constructor Function

  • Constructors are functions that create new objects. They define properties and behaviors that will belong to the new object. Think of them as a blueprint for the creation of new objects.

  • Here is an example of a constructor:

function Dog() {
  this.name = "Anakin";
  this.color = "brown";
  this.numLegs = 4;
}
Enter fullscreen mode Exit fullscreen mode
  • This constructor defines a Dog object with properties name, color, and numLegs set to Anakin, brown, and 4, respectively. Constructors follow a few conventions:
  1. Constructors are defined with a capitalized name to distinguish them from other functions that are not constructors.

  2. Constructors use the keyword this to set properties of the object they will create. Inside the constructor, this refers to the new object it will create.

  3. Constructors define properties and behaviors instead of returning a value as other functions might.

Top comments (0)

Some comments have been hidden by the post's author - find out more