Javascript Class Computed Member Names

Introduction

Class methods and accessor properties can also have computed names.

Instead of using an identifier, use square brackets around an expression.

let methodName = "sayName";

class Person {/*  w ww .j  a  v a  2  s.c  o m*/

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

    [methodName]() {
        console.log(this.name);
    }
}

let me = new Person("CSS");
me.sayName();           // "CSS"

Accessor properties can use computed names:

let propertyName = "html";

class MyElement {/* www .  j  ava2s . co  m*/

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

    get [propertyName]() {
        return this.element.innerHTML;
    }

    set [propertyName](value) {
        this.element.innerHTML = value;
    }
}
 



PreviousNext

Related