Add a method to a JavaScript object constructor?


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.

Example

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

Live Demo

<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("Trump", "$28.05billion", "73", "President");
   document.write(person1.name());
</script>
</body>
</html>

Output

Trump
raja
Published on 07-Aug-2019 11:57:30
Advertisements