다음은 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: rebeccapurple; } </style> </head> <body> <h1>Access an object through another object in JavaScript</h1> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3>Click on the above button to display obj2</h3> <script> let resEle = document.querySelector(".result"); let BtnEle = document.querySelector(".Btn"); let obj = { firstName: "Rohan", lastName: "Sharma", welcome() { return "Welcome " + this.firstName + " " + this.lastName; }, }; let obj2 = { firstName: "Mohit", lastName: obj.lastName, welcomeString: obj.welcome(), }; BtnEle.addEventListener("click", () => { resEle.innerHTML = "obj2.firstName = " + obj2.firstName + "<br>"; resEle.innerHTML += "obj2.lastName = " + obj2.lastName + "<br>"; resEle.innerHTML += "obj2.welcomeString = " + obj2.welcomeString + "<br>"; }); </script> </body> </html>
출력
위의 코드는 다음과 같은 출력을 생성합니다 -
'여기를 클릭' 버튼을 클릭하면 -