Access property as a property using 'get' in JavaScript?

JavascriptObject Oriented ProgrammingFront End Technology

Using getter in javascript we can able to access the property as a property in a different way. The keyword 'get' is used to make this process happen. Let's discuss it in a nutshell.

Example

In the following example, the property 'details' is used as a function that is 'details()'. Therefore we will get no results. Instead, if we remove the parenthesis brackets, the keyword 'get' make sure to treat the property "details" as property but not as a function.

<html>
<body>
<p id = "prop"></p>
<script>
   var business = {
      product: "Tutorix",
      parent : "Tutorialspoint",
      get details() {
         return this.product+" is the product of" + " " + this.parent;
      }
   };
   document.getElementById("prop").innerHTML = business.details();
</script>
</body>
</html>

Example

Here since the parenthesis brackets were removed, the 'get' keyword makes sure that to treat the property "details" as property but not a function.

Live Demo

<html>
<body>
<p id = "prop"></p>
<script>
   var business = {
      product: "Tutorix",
      parent : "Tutorialspoint",
      get details() {
         return this.product+" is the product of" + " " + this.parent;
      }
   };
   document.getElementById("prop").innerHTML = business.details;
</script>
</body>
</html>

Output

Tutorix is the product of Tutorialspoint
raja
Published on 07-Aug-2019 08:53:51
Advertisements