ES6 Dynamic class names

前端 未结 6 1862
故里飘歌
故里飘歌 2020-11-27 17:45

I have been experimenting with ES6 classes and am wondering if you can change class names dynamically? For example

class [Some dynamic name] {}; 

6条回答
  •  鱼传尺愫
    2020-11-27 18:30

    There is a pretty simple way to do it:

    const nameIt = (name, cls) => ({[name] : class extends cls {}})[name];
    

    Here's the demo.

    It uses an object literal to define a field with a desired name that would hold a new class. This causes the new class to automatically get the desired name. After we're done with that, we extract that new class and return it.

    Note the parens around the object literal, so that curly braces don't get mistaken for a code block (...) => {...}.

    Of course, putting an existing class into named fields won't change the class, so this only works if you are creating a new class. If you only need a dynamic name in one place where you define the class you are naming, you can drop an extra inheritance and just go:

    const myClass = {[name]: class {
        ...
    }}[name];
    

提交回复
热议问题