ES6 Dynamic class names

前端 未结 6 1860
故里飘歌
故里飘歌 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

    One way, even if not ideal, is simple with eval:

    ~function() {
        const name = "Lorem"
    
        eval(`
            var ${name} = class ${name} {} 
        `)
    
        console.log(Lorem) // class Lorem {}
    }()
    

    Note, it has to be with var. Using let, const, and plain class inside the eval won't work.

    Another way with Function:

    ~function() {
        const name = "Lorem"
    
        const c = new Function(`
            return class ${name} {}
        `)()
    
        console.log(c) // class Lorem {}
    }()
    

    Sitenote: you can pass scope variables into the Function and use them inside:

    ~function() {
        const name = "Lorem"
        const val = "foo"
    
        const Class = new Function('val', `
            return class ${name} {
                constructor() {
                    console.log( val )
                }
            }
        `)( val )
    
        console.log(Class) // class Lorem {}
        new Class // "foo"
    }()
    

提交回复
热议问题