getters and setters in JavaScript classes?

JavascriptObject Oriented ProgrammingFront End Technology

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

In the following example, getters and setters were added to the class 'Company' and the property value is obtained by using a 'get' keyword. 

Live Demo

<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
raja
Published on 02-Aug-2019 15:55:16
Advertisements