Convert a string to a template string

前端 未结 19 2391
轮回少年
轮回少年 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:09

    What you're asking for here:

    //non working code quoted from the question
    let b=10;
    console.log(a.template());//b:10
    

    is exactly equivalent (in terms of power and, er, safety) to eval: the ability to take a string containing code and execute that code; and also the ability for the executed code to see local variables in the caller's environment.

    There is no way in JS for a function to see local variables in its caller, unless that function is eval(). Even Function() can't do it.


    When you hear there's something called "template strings" coming to JavaScript, it's natural to assume it's a built-in template library, like Mustache. It isn't. It's mainly just string interpolation and multiline strings for JS. I think this is going to be a common misconception for a while, though. :(

提交回复
热议问题