Press "Enter" to skip to content

Object Constructor function – Object Oriented Programming in JavaScript

One of the easiest ways of defining an Object is using a constructor function. Object Constructor function helps to create different instances of an object  using the same function.
Constructor function is not much different from other normal JavaScript functions. The main difference between a ”constructor function and a normal JavaScript function is that the constructor function is invoked using the “new” operator.

Defining an Object using a Constructor function

Let’s create a constructor function named “Person“.  We will use “name“,”age“,”gender” as the properties and “talk” as the method for the “Person” ‘class’ constructor function. The code looks like below:

“personA” and “personB” are two different instances of the Person ‘class’. Both these instances do inherit all the properties and methods of the Person ‘class’.  Any modifications or changes to the Person ‘class’ properties or methods will be available in all its instances as well.

Adding  new  Methods to the constructor using Prototype

Below function will add a new method (reduceAge) to the Person ‘Class’. Once this method is invoked it will reduce the age value by the number passed as the argument into this function. Below is the example.

Creating a simple constructor function is very simple as above!