Computer >> Computer tutorials >  >> Programming >> Javascript

getters and setters in JavaScript classes?


Classes allow using getters and setters. It is smart to use getters and setters for the properties, especially if you want to do something special with the value before returning them, or before you set them. To add getters and setters in the class, use the get and set keywords.

Example

<html>
<body>
<p id="method"></p>
<script>
   class Company {
      constructor(brand) {
         this.Compname = brand;
      }
      get name() {
         return this.Compname;
      }
      set name(x) {
         this.Compname = x;
      }
   }
   myName = new Company("Tutorialspoint");
   document.getElementById("method").innerHTML = myName.Compname;
</script>
</body>
</html>

Output

Tutorialspoint