访问器属性

自有属性需要在类构造器中创建,而类还允许你在原型上定义访问器属性。为了创建一个 getter,要使用 get 关键字,并要与后方标识符之间留出空格;创建 setter 用相同方式,只是要换用 set 关键字。例如:

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

此代码中的 CustomHTMLElement 类用于包装一个已存在的 DOM 元素。它的属性 html 拥有 gettersetter,委托了元素自身的 innerHTML 方法。该访问器属性被创建在 CustomHTMLElement.prototype 上,并且像其他类属性那样被创建为不可枚举属性。非类的等价表示如下:

// 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;
}());

正如之前的例子,此例说明了使用类语法能够少写大量的代码。仅仅为 html 访问器属性定义的代码量,就几乎相当于等价的类声明的全部代码量了。