How to access an object through another object in JavaScript?


Following is the code to access an object through another object 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: 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>

Output

The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 21-Jul-2020

365 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements