JavaScript Object Accessors

JavascriptWeb DevelopmentObject Oriented Programming

The getter and setter keyword are used for accessing the objects. The getter return value is used when a property is being accessed and the setter takes an argument and sets the property value inside the object to that passed argument.

Following is the code for accessing objects 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;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
      color: red;
   }
</style>
</head>
<body>
<h1>JavaScript Object Accessors</h1>
Enter a number <input class="num" type="number" />
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above button to set the age value and display it
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   let testObj = {
      age: "",
      set AGE(val) {
         this.age = val;
      },
      get AGE() {
         return this.age;
      },
   };
   document.querySelector(".Btn").addEventListener("click", () => {
      let number = document.querySelector(".num").value;
      testObj.AGE = number;
      sampleEle.innerHTML = "AGE = " + testObj.AGE;
   });
</script>
</body>
</html>

Output

On entering a number and clicking on ‘CLICK HERE’ button −

raja
Updated on 11-May-2020 13:55:31

Advertisements