English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Getters and setters in JavaScript classes?

The class allows the use of getters and setters. It is wise to use getters and setters for properties, especially if you want to perform special processing on the value before or after returning it. To add getters and setters in a 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("w3codebox());
   document.getElementById("method").innerHTML = myName.Compname;
</script>
</body>
</html>

Output Result

w3codebox