Computer >> Computer tutorials >  >> Programming >> Javascript

How to add a method to a JavaScript object?


Adding a method to the object

Adding a method to a javascript object is easier than adding a method to an object constructor. We need to assign the method to the existing property to ensure task completion.

Example

In the following example, initially, the object type is created and later on, the properties of the object were created. Once the creation of properties is done, a method is assigned to each of the objects and the properties were accessed using the method as our requirement.

<html>
<body>
<p id = "prop"></p>
<script>
   function Business(name, property, age, designation) {
      this.Name = name;
      this.prop = property;
      this.age = age;
      this.designation = designation;
   }
   var person1 = new Business("Trump", "$28.05billion", "73", "President");
   var person2 = new Business("Jackma", "$35.6 billion", "54", "entrepeneur");
   person1.det = function() {
      return this.Name + " "+" has a property of net worth "+ "" + this.prop;
   };
   person2.det = function() {
      return this.Name + " "+" has a property of net worth "+ "" + this.prop;
   };
   document.write(person2.det() +" and "+person1.det());
</script>
</body>
</html>

Output

Jackma has a property of net worth $35.6 billion and Trump has a property of net worth $28.05billion