How to share private members among common instances in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

Following is the code for sharing private members among common instances in JavaScript −

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: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Share private members among common instances in JavaScript</h1>
<div class="result"></div>
<br />
<button class="Btn">Click Here</button>
<h3>Click on the above button to display the personName property</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   function Person(name) {
      let personName = name;
      this.returnName = function () {
         return personName;
      };
   }
   let person1 = new Person("Rohan");
   let person2 = new Person("Shawn");
   BtnEle.addEventListener("click", () => {
      resEle.innerHTML =
      "person1.returnName() = " + person1.returnName() + "<br>";
      resEle.innerHTML +=
      "person1.returnName() = " + person2.returnName() + "<br>";
      resEle.innerHTML +=
      "person1.personName = " + person1.personName + "<br>";
      resEle.innerHTML +=
      "person2.personName = " + person2.personName + "<br>";
   });
</script>
</body>
</html>

Output

On clicking the ‘Click Here’ button −

raja
Published on 18-Jul-2020 11:51:09
Advertisements