DEV Community

Steven Frasica
Steven Frasica

Posted on

Constructors & Objects

When creating objects, you can save a lot of time by using constructor functions. Constructor functions essentially act like a factory that can quickly create new objects. After initial setup, you'll only need to pass in different parameters into the function for each new object.

A constructor function is like a regular old function, but with a few differences.

  • Capitalize constructor functions to distinguish it from a regular function
  • Each parameter passed into a constructor function will serve as the value of a variable in the object. Since we're working with objects, that variable is a property of the object.
  • Use the keyword new when creating a new object with a constructor function
function Monster(age, color, snack, hobby) {
  this.age = age,
  this.color = color,
  this.snack = snack,
  this.hobby = hobby

const creepy = new Monster(1001, "blue", "rocks", "knitting");

const spooky = new Monster(500, "purple", "brains", "reading");

Above is the constructor function definition for Monster. It takes in four parameters, which are then used to assign values to the Monster object's properties.

The monster creepy was used by calling the Monster constructor function with four arguments and the new keyword. The this keyword is used to refer to the property of the object being defined. The object is this.

It is helpful to keep track of properties and parameters by assigning them the same name. It is not necessary, but it will avoid confusion when you're working with many properties.

Lastly, we can use dot notation to refer to the value of an object's property.

//Output is 1001

//Output is "blue"

//Output is "reading"

Constructor functions will save you a lot of time in the long run when you have to create multiple objects with similar properties.

Discussion (0)