Class expressions in object initializers.
/#!/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
What would be a use case for this?
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.
/#!/JoePea schrieb:
A use case could be to dynamically name a class at runtime without
eval
.let o = { [name]() {} }
produces a named function inside ofo
(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
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.
We can currently do