Convert a string to a template string

前端 未结 19 2395
轮回少年
轮回少年 2020-11-22 08:30

Is it possible to create a template string as a usual string

let a=\"b:${b}\";

an then convert it into a template string

le         


        
19条回答
  •  执念已碎
    2020-11-22 09:11

    The issue here is to have a function that has access to the variables of its caller. This is why we see direct eval being used for template processing. A possible solution would be to generate a function taking formal parameters named by a dictionary's properties, and calling it with the corresponding values in the same order. An alternative way would be to have something simple as this:

    var name = "John Smith";
    var message = "Hello, my name is ${name}";
    console.log(new Function('return `' + message + '`;')());
    

    And for anyone using Babel compiler we need to create closure which remembers the environment in which it was created:

    console.log(new Function('name', 'return `' + message + '`;')(name));
    

提交回复
热议问题