Class expressions in object initializers.

# /#!/JoePea (8 years ago)

We can currently do

let dynamicName = "foo"
let o = {
  [dynamicName]() { /* ... */ }
}
console.log(o.foo) // logs the function
​```​

Might be nice to be able to do it with classes too:

```js
let dynamicName = "foo"
let o = {
  class [dynamicName] { /* ... */ }
}
console.log(o.foo) // logs the class
​```​
# Bergi (8 years ago)

/#!/JoePea wrote:

Might be nice to be able to do it with classes too:

let dynamicName = "foo"
let o = {
  class [dynamicName] { /* ... */ }
}
console.log(o.foo) // logs the class
​```​

You can already do

let dynamicNAme = "foo"; let o = { [dynamicName]: class { … } };

but I can see absolutely no reason why you'd want to put a class inside an object literal.

Bergi

# Blake Regalia (8 years ago)

What would be a use case for this?

# /#!/JoePea (8 years ago)

A use case could be to dynamically name a class at runtime without eval. let o = { [name]() {} } produces a named function inside of o (at least in Chrome) without needing eval, and then we can extract it from the object.

# Bergi (8 years ago)

/#!/JoePea schrieb:

A use case could be to dynamically name a class at runtime without eval. let o = { [name]() {} } produces a named function inside of o (at least in Chrome) without needing eval, and then we can extract it from the object.

If you just want to name a class, there are much easier ways to do that:

let x = class { get name() { return dynamicName; } … };

or

class x { … } Object.defineProperty(x, "name", { value: dynamicName });

Kind , Bergi

# Blake Regalia (8 years ago)

A reference to a class is simply a variable. Variables only exist within a certain scope. When using a variable, its name is essentially irrelevant so long as you, the developer, understand what it refers to.

If its necessary to distinguish between multiple instances of an object that were created in response to an unpredictable input, then what you really need are properties (e.g., keys and values, where the keys reflect the 'dynamic' name), as Bergi points out.