DEV Community

 Bishnu Prasad Chowdhury
Bishnu Prasad Chowdhury

Posted on

Constructor functions in JavaScript

Constructor functions are regular functions in JavaScript that can be used to create objects that have similar methods and properties.

In a normal scenario, we would use object literals to create objects with certain characteristics like below:

var Image = {
    URL: "https://www.domain.com/image.jpg",
    height: 400,
    width: 400
};

Image.URL
>"https://www.domain.com/image.jpg"
Image.height
>400
Image.width
>400

Enter fullscreen mode Exit fullscreen mode

But when we have to deal with multiple objects with similar characteristics, then we can use the constructor function to declare a characteristic and then reuse it by creating objects of that function again and again.

So in a constructor function, we declare the properties with "this" keyword and we create an object of the function with the "new" keyword like below and we have to pass the arguments to the function which is to be used during object creation:

var Image = function(URL, width, height) {
    this.URL = URL; 
    this.width = width;
    this.height = height;
};

var img1 = new Image ("https://www.domain.com/img1", 400, 600);
var img2 = new Image ("https://www.domain.com/img2", 500, 500);

img1.URL
>"https://www.domain.com/img1"

img1.height
>600

img2. width
>500

Enter fullscreen mode Exit fullscreen mode

Unlike normal functions, constructor functions are named with their first letter in uppercase.

We can also set a new property of the constructor function separately using the prototype object where all the objects created from the constructor function can make use of it.
Suppose we want to add a new property opacity to the Image function without disturbing the main code, we should do like below:

var Image = function(URL, width, height) {
    this.URL = URL; 
    this.width = width;
    this.height = height;
};

var img1 = new Image ("https://www.domain.com/img1", 500, 500);
var img2 = new Image ("https://www.domain.com/img2", 600, 600);

Image.prototype.opacity = 0;

img1.opacity
>0

img2.opacity
>0

Enter fullscreen mode Exit fullscreen mode

For normal functions, the default return type is of Undefined type, whereas the default return type of Constructor functions is "this" parameter.

function normalFunc() {}
var cf = function ConstructorFunction() {}

var a = new cf ();
var b = normalFunc();

a
>ConstructorFunction {}

b
>undefined

Enter fullscreen mode Exit fullscreen mode

Top comments (0)