ต่อไปนี้เป็นรหัสสำหรับการแบ่งปันสมาชิกส่วนตัวระหว่างอินสแตนซ์ทั่วไปใน JavaScript -
ตัวอย่าง
<!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>
ผลลัพธ์
เมื่อคลิกปุ่ม 'คลิกที่นี่' -