Adding methods to Javascript Prototypes

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for adding methods to JavaScript prototypes −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 20px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Adding methods to Javascript Prototypes</h1>
<div class="result"></div>
<br />
<button class="Btn">Click Here</button>
<h3>Click on the above button to call the methods of person1 and person2 object</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function personConstructor(fName, lName, birthYear) {
      this.fName = fName;
      this.lName = lName;
      this.birthYear = birthYear;
   }
   personConstructor.prototype.welcome = function () {
      return "Welcome " + this.fName + " " + this.lName;
   };
   personConstructor.prototype.calcAge = function () {
      return "Your age = " + (new Date().getFullYear() - this.birthYear);
   };
   let person1 = new personConstructor("Rohan", "Sharma", 1995);
   let person2 = new personConstructor("Shawn", "Smith", 1992);
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML = "person1.welcome() = " + person1.welcome() + "<br>";
      resEle.innerHTML += "person1.calcAge() = " + person1.calcAge() + "<br>";
      resEle.innerHTML += "person2.welcome() = " + person2.welcome() + "<br>";
      resEle.innerHTML += "person2.calcAge() = " + person2.calcAge() + "<br>";
   });
</script>
</body>
</html>

Output

On clicking the ‘Click Here’ button −

raja
Published on 18-Jul-2020 11:22:57
Advertisements