Add a method to a JavaScript object constructor?


In this article we are going to discuss how to add a method to a JavaScript object constructor with suitable examples in JavaScript.

In JavaScript adding a method to an object constructor is unlike adding a method to a normal object. We cannot add a method as it is the case with a normal object. To make a method in an object constructor it has to be added inside the object constructor.

Let’s understand this concept in a better way with the help of the examples further in this article.

Example 1

In the following example, the method is added inside the constructor, therefore, we have got a legitimate value.

<html>
<body>
   <script>
      function Business(name, property, age, designation) {
         this.Name = name;
         this.prop = property;
         this.age = age;
         this.designation = designation;
         this.name = function() {
            return this.Name
         };
      }
      var person1 = new Business("Bill gates", "$28.05billion", "71", "Owner");
      document.write(person1.name());
   </script>
</body>
</html>

On executing the above code, the below output is generated.

Example 2

This is another example program to add a method to the JS object contructor.

<!DOCTYPE html>
<html>
<head>
   <title>To add a method to a JavaScript Object Constructor.</title>
</head>
<body style="text-align : center">
   <h3>Add a method to a JavaScript Object Constructor.</h3>
   <p id="method-to-obj-constructor"></p>
   <script>
      function Car(name, model, year, color) {
         this.Name = name;
         this.Model = model;
         this.Year = year;
         this.Color = color;
         this.type = 'SUV';
         this.description = function() {
            return this.Name+" is of "+this.Model+" model and launched in the year "+this.Year+" and is of "+this.type+" type."
         }
      }
      var car1 = new Car("Maruti", "Vitara Brezza", "2016", "Red");
      document.getElementById("method-to-obj-constructor").innerHTML = car1.description();
   </script>
</body>
</html>

On executing the above code, the below output is generated.

Updated on: 09-Dec-2022

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements