DEV Community

Cover image for Understanding Constructor Functions in JavaScript
Stacy Daniel
Stacy Daniel

Posted on

Understanding Constructor Functions in JavaScript

What is a constructor ?

In Javascript, a constructor is a special function which creates an instance of a class which is typically called an "object". They are technically regular functions, but What makes them special is that they are always invoked with a powerful operator in JavaScript called the new operator. Constructors provide the means to create as many objects as needed, whilst attaching properties and behaviors to them as required. As convention, the constructor function name usually starts with a capital letter, to be easily recognizable in code.

What happens when a constructor gets called ?

When a Constructor is invoked:

  • A new empty object is created.
  • The Javascript keyword this starts to refer to the newly created object.
  • The value of the newly created object this is then returned.

Example

here is an example of a Bird constructor, which will allow us to create new objects:

     function Bird() {
       this.name = "Tweety";
       this.color = "blue";
     }      

  let blueBird = new Bird();
Enter fullscreen mode Exit fullscreen mode

this inside the constructor always refers to the object being created.

When calling a constructor, the new operator is used to tell Javascript to create a new instance of the Bird constructor that is called blueBird. Note that the constructor function is not changed, the newly created new context is changed! Without the new operator, this inside the constructor would not point to the newly created object, giving unexpected results. when a constructor is invoked without the new operator it is invoked as a regular JavaScript function.

Summary

Note the main purpose of constructors are to implement reusable object creation code.

  • Constructor functions are regular functions but with a common agreement to defined them with the first letter capitalized.

  • Constructors use the keyword this to set properties of the object they will create.

  • Constructor functions can be used to create multiple similar objects.

Thank you for reading this article, I hope you found it useful. Happy Coding 😀

Top comments (0)