Skip to main content

Welcome to a Grasp lesson

Create a free account to keep studying and create your own study path.

Lesson 39

Dynamic Class Members and Computed Method Names

This lesson is built with resources from exploringjs.com and developer.mozilla.org.

Hello! Let's dive into the next lesson in our "Advanced OOP: Classes and Encapsulation" module.

In the previous lesson, we explored static initialization blocks, which allow for complex logic to run once at class definition time. We saw how to handle setup, manage errors, and even create privileged functions. Today, we'll continue exploring dynamic class features, but we'll shift our focus from definition-time logic to definition-time structure.

The learning outcome for this lesson is to create computed method names and dynamic class members. You'll learn how to define the names of your class methods and properties using variables and expressions, making your class definitions more flexible and powerful.

The Foundation: Computed Property Names in Objects

Before we even get to classes, it's important to remember that this feature was introduced in ES6 for object literals. You might have encountered this before. The syntax is simple: you wrap an expression in square brackets [] where a property name would normally go. The result of the expression becomes the property key.

This is extremely useful for creating properties based on runtime data.

Dynamically Computed Property Names in JavaScript
This image illustrates the core concept of computed property names in the context of plain objects. We will now see how this exact same principle applies to class definitions.

Dynamic Methods in Classes

The same [expression] syntax that works for object literals also works inside class definitions for methods, getters, setters, and even static members. This allows the very structure of your class to be determined dynamically when it's defined.

Let's look at the basic syntax.

Method definitions - JavaScript - MDN Web Docs

The MDN Web Docs for 'Method definitions' provides the official syntax and a clear example of computed property names. It's a great starting point to see how this fits into the language specification.

First, review the 'Syntax' section, noting the lines that include [expression]. Then, read the short section titled 'Computed property names' to see a practical example within an object literal.

Now, let's see this applied directly within a class. The following three class definitions are functionally identical, but the second and third use computed names.

// 1. Standard method definition
class Greeter {
  sayHello() {
    return "Hello!";
  }
}

// 2. Computed from a concatenated string
const methodName = "Hello";
class Greeter {
  ['say' + methodName]() {
    return "Hello!";
  }
}

// 3. Computed from a variable
const fullMethodName = 'sayHello';
class Greeter {
  [fullMethodName]() {
    return "Hello!";
  }
}

const g = new Greeter();
console.log(g.sayHello()); // "Hello!"

A Critical Use Case: Methods with Symbol Keys

This feature isn't just for convenience; it's essential for a key part of modern JavaScript. As we covered in Module 1, Symbols are often used as unique keys for special, built-in object behaviors.

How do you define a method whose name is a Symbol? You can't type a Symbol literally as a method name. The only way to do it is with a computed property name.

Computed method names in classes

The 'Exploring JS' book by Dr. Axel Rauschmayer has a concise section that directly explains this concept and, more importantly, connects it to Symbols.

Please read the section 'Computed method names' (15.2.2.4). Pay close attention to the example that uses Symbol.iterator. This demonstrates the primary reason this feature is so important.

As you saw in the reading, if you want a class to be iterable (i.e., work with the for...of loop), it needs a method with the key Symbol.iterator. Computed property syntax is the mechanism to achieve this:

class Log {
  constructor(...messages) {
    this.messages = messages;
  }

  // This method makes instances of Log iterable.
  // We MUST use computed property syntax to use the Symbol as a key.
  *[Symbol.iterator]() {
    for (const msg of this.messages) {
      yield `[LOG] ${msg}`;
    }
  }
}

const myLog = new Log("Server started", "DB connected", "User logged in");

for (const entry of myLog) {
  console.log(entry);
}
// Output:
// [LOG] Server started
// [LOG] DB connected
// [LOG] User logged in

This pattern applies to all well-known Symbols that define object behavior, such as Symbol.toPrimitive, Symbol.hasInstance, and more, solidifying the bridge between the Symbol system and class syntax.


Dynamic Class Structure for Metaprogramming

Beyond Symbols, computed method names unlock patterns where the shape of a class is determined by external configuration. This is a form of metaprogramming—writing code that operates on other code.

Imagine you're building a generic "Model" class for an application. The fields of the model are defined in a schema. You could write a class that reads this schema and automatically creates getter methods for each field.

const userSchema = {
  fields: ['id', 'username', 'email']
};

class Model {
  constructor(data) {
    this._data = data;
  }

  // This is a simple implementation. In a real scenario,
  // this logic might be in a factory function or a more complex setup.
  // For simplicity, we'll define the methods directly here.
}

// It's more common to do this with a factory function that creates the class
function createModelClass(schema) {
  return class {
    constructor(data) {
      this._data = data;
    }

    // Dynamically add getter methods
    static { // Using a static block to contain this logic
      for (const field of schema.fields) {
        // Create a capitalized getter name, e.g., 'getUsername'
        const getterName = `get${field.charAt(0).toUpperCase() + field.slice(1)}`;

        // Add the method to the prototype
        this.prototype[getterName] = function() {
          return this._data[field];
        }
      }
    }
  }
}

const User = createModelClass(userSchema);

const user = new User({
  id: 1,
  username: 'Kiyotaka',
  email: 'ayanokoji@example.com'
});

console.log(user.getUsername()); // "Kiyotaka"
console.log(user.getEmail());    // "ayanokoji@example.com"
// console.log(user.getPassword()); // Would be undefined, as it wasn't in the schema

In the example above, we used a factory function and modified the prototype directly. While you cannot use a for loop to create methods directly inside the class body syntax itself, this pattern of dynamically adding methods to the prototype is a powerful application of the same underlying principle. The core idea is using runtime data (the schema) to define the class structure.

Test your understanding!

Your task is to create a Dispatcher class that can register and trigger events. The methods for triggering events should be created dynamically based on a list of event names.

Requirements:

  1. The Dispatcher's constructor should accept an array of eventNames (e.g., ['login', 'logout', 'error']).
  2. The class should have a handlers property, which is an object to store event listeners.
  3. The class must have a public method on(eventName, callback) to register a listener for an event.
  4. For each event name in the eventNames array provided to the constructor, you must dynamically create a method on the class prototype that triggers that event.
    • For example, if eventNames contains 'login', you should be able to call dispatcher.triggerLogin(data).
    • The dynamic method name should be trigger<EventName> with the event name capitalized (e.g., login -> triggerLogin).
    • This method should accept one argument (data) and call all registered handlers for that event, passing data to them.

Hint: You'll likely need to add the methods to the class's prototype inside the constructor.

Start with this template:

class Dispatcher {
  constructor(eventNames) {
    this.handlers = {};
    
    // TODO: Loop through eventNames and create dynamic trigger methods
    // on `this.constructor.prototype`.
  }

  on(eventName, callback) {
    if (!this.handlers[eventName]) {
      this.handlers[eventName] = [];
    }
    this.handlers[eventName].push(callback);
  }
}

// --- Test cases ---
const appEvents = new Dispatcher(['login', 'logout']);

appEvents.on('login', (user) => {
  console.log(`${user.name} logged in.`);
});

appEvents.on('login', (user) => {
    if (user.isAdmin) {
        console.log("Admin user detected.");
    }
});

appEvents.on('logout', () => {
  console.log('User logged out.');
});

// These methods should exist because of your dynamic creation!
appEvents.triggerLogin({ name: 'Asuka', isAdmin: true });
appEvents.triggerLogout();

/*
Expected Output:
Asuka logged in.
Admin user detected.
User logged out.
*/
Show answer

Here's a complete solution:

class Dispatcher {
  constructor(eventNames) {
    this.handlers = {};

    for (const eventName of eventNames) {
      // Capitalize the event name for the method, e.g., "login" -> "Login"
      const capitalizedEventName = eventName.charAt(0).toUpperCase() + eventName.slice(1);
      const methodName = `trigger${capitalizedEventName}`;

      // Use a computed property name to define the method on the prototype.
      // We do this on the prototype so the method is only created once and shared
      // by all instances, rather than being recreated for every new Dispatcher.
      // We check if the method already exists to avoid redefining it if multiple
      // instances with the same event names are created.
      if (!this.constructor.prototype[methodName]) {
          this.constructor.prototype[methodName] = function(data) {
            const registeredHandlers = this.handlers[eventName];
            if (registeredHandlers) {
              registeredHandlers.forEach(handler => handler(data));
            }
          }
      }
    }
  }

  on(eventName, callback) {
    if (!this.handlers[eventName]) {
      this.handlers[eventName] = [];
    }
    this.handlers[eventName].push(callback);
  }
}


// --- Test cases ---
const appEvents = new Dispatcher(['login', 'logout']);

appEvents.on('login', (user) => {
  console.log(`${user.name} logged in.`);
});

appEvents.on('login', (user) => {
    if (user.isAdmin) {
        console.log("Admin user detected.");
    }
});

appEvents.on('logout', () => {
  console.log('User logged out.');
});

appEvents.triggerLogin({ name: 'Asuka', isAdmin: true });
appEvents.triggerLogout();

This solution correctly iterates through the event names and dynamically adds a corresponding trigger method to the class prototype. This is an efficient pattern because the methods are defined once and shared across all instances of Dispatcher.


Conclusion

You have now learned how to make your class definitions themselves dynamic. By using computed property names, you can define the structure of your classes based on variables, expressions, and configuration data.

Key Takeaways:

  • The [expression] syntax allows you to use the result of an expression as a method or property name within a class, just as in an object literal.
  • This feature is not just a convenience; it is the required mechanism for defining methods whose names are Symbols (e.g., [Symbol.iterator]).
  • You can use this capability for metaprogramming patterns, creating flexible classes whose structure is determined by runtime configuration, leading to more generic and reusable code.

Next Up

We have spent this module mastering the class keyword—from inheritance and static members to private fields and dynamic structures. In the next and final lesson of this module, we will explore a powerful application of these concepts: learning how to extend built-in classes like Array or Error to create specialized versions. This will allow you to create custom, powerful data structures and error types that integrate seamlessly with the rest of the JavaScript language.