다음은 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>
출력
'여기를 클릭' 버튼을 클릭하면 -