Javascript Class Accessor Properties

Introduction

Javascript 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, use the keyword set. For example:

class MyElement {//w  ww. j  a v a2  s. c  om

    constructor(element) {
        this.element = element;
    }

    get html() {
        return this.element.innerHTML;
    }

    set html(value) {
        this.element.innerHTML = value;
    }
}

var descriptor = Object.getOwnPropertyDescriptor(MyElement.prototype, "html");
console.log("get" in descriptor);   // true
console.log("set" in descriptor);   // true
console.log(descriptor.enumerable); // false

 



PreviousNext

Related