ต่อไปนี้เป็นรหัสเพื่อเข้าถึงวัตถุผ่านวัตถุอื่นใน 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>
ผลลัพธ์
รหัสข้างต้นจะสร้างผลลัพธ์ต่อไปนี้ -
เมื่อคลิกปุ่ม 'คลิกที่นี่' -