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:
class CustomHTMLElement {
constructor(element) {
this.element = element;
}
get html() {
return this.element.innerHTML;
}
set html(value) {
this.element.innerHTML = value;
}
}
var descriptor = Object.getOwnPropertyDescriptor(CustomHTMLElement.prototype, "html");
console.log("get" in descriptor); // true
console.log("set" in descriptor); // true
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:
// direct equivalent to previous example
let CustomHTMLElement = (function() {
"use strict";
const CustomHTMLElement = function(element) {
// make sure the function was called with new
if (typeof new.target === "undefined") {
throw new Error("Constructor must be called with new.");
}
this.element = element;
}
Object.defineProperty(CustomHTMLElement.prototype, "html", {
enumerable: false,
configurable: true,
get: function() {
return this.element.innerHTML;
},
set: function(value) {
this.element.innerHTML = value;
}
});
return CustomHTMLElement;
}());
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.