Accessor Properties

While own properties should be created inside class constructors, classes allow you to define accessor properties on the prototype. To create a getter, use the keyword get followed by a space, followed by an identifier; to create a setter, do the same using the keyword set. For example:

  1. class CustomHTMLElement {
  2. constructor(element) {
  3. this.element = element;
  4. }
  5. get html() {
  6. return this.element.innerHTML;
  7. }
  8. set html(value) {
  9. this.element.innerHTML = value;
  10. }
  11. }
  12. var descriptor = Object.getOwnPropertyDescriptor(CustomHTMLElement.prototype, "html");
  13. console.log("get" in descriptor); // true
  14. console.log("set" in descriptor); // true
  15. console.log(descriptor.enumerable); // false

In this code, the CustomHTMLElement class is made as a wrapper around an existing DOM element. It has both a getter and setter for html that delegates to the innerHTML property on the element itself. This accessor property is created on the CustomHTMLElement.prototype and, just like any other method would be, is created as non-enumerable. The equivalent non-class representation is:

  1. // direct equivalent to previous example
  2. let CustomHTMLElement = (function() {
  3. "use strict";
  4. const CustomHTMLElement = function(element) {
  5. // make sure the function was called with new
  6. if (typeof new.target === "undefined") {
  7. throw new Error("Constructor must be called with new.");
  8. }
  9. this.element = element;
  10. }
  11. Object.defineProperty(CustomHTMLElement.prototype, "html", {
  12. enumerable: false,
  13. configurable: true,
  14. get: function() {
  15. return this.element.innerHTML;
  16. },
  17. set: function(value) {
  18. this.element.innerHTML = value;
  19. }
  20. });
  21. return CustomHTMLElement;
  22. }());

As with previous examples, this one shows just how much code you can save by using a class instead of the non-class equivalent. The html accessor property definition alone is almost the size of the equivalent class declaration.