Computed Member Names

The similarities between object literals and classes aren’t quite over yet. Class methods and accessor properties can also have computed names. Instead of using an identifier, use square brackets around an expression, which is the same syntax used for object literal computed names. For example:

  1. let methodName = "sayName";
  2. class PersonClass {
  3. constructor(name) {
  4. this.name = name;
  5. }
  6. [methodName]() {
  7. console.log(this.name);
  8. }
  9. }
  10. let me = new PersonClass("Nicholas");
  11. me.sayName(); // "Nicholas"

This version of PersonClass uses a variable to assign a name to a method inside its definition. The string "sayName" is assigned to the methodName variable, and then methodName is used to declare the method. The sayName() method is later accessed directly.

Accessor properties can use computed names in the same way, like this:

  1. let propertyName = "html";
  2. class CustomHTMLElement {
  3. constructor(element) {
  4. this.element = element;
  5. }
  6. get [propertyName]() {
  7. return this.element.innerHTML;
  8. }
  9. set [propertyName](value) {
  10. this.element.innerHTML = value;
  11. }
  12. }

Here, the getter and setter for html are set using the propertyName variable. Accessing the property by using .html only affects the definition.

You’ve seen that there are a lot of similarities between classes and object literals, with methods, accessor properties, and computed names. There’s just one more similarity to cover: generators.