Home > Article > Web Front-end > Can ES6 Template Literals be Truly Reusable?
Reusability conundrum in ES6 Template Literals
The primary concern raised in this discussion revolves around the presumed lack of reusability in ES6 template literals. Conventional demonstrations emphasize substitutions at declaration time, disallowing runtime modification.
Solution: Leveraging the Function Constructor
To address this issue, a viable solution emerges in the form of the Function constructor. This approach involves converting the template string into a function.
Consider the following snippet:
<code class="js">const templateString = `Hello ${this.name}!`; const templateVars = { name: "world" }; const fillTemplate = function(templateString, templateVars){ return new Function("return `" + templateString + "`;").call(templateVars); }; console.log(fillTemplate(templateString, templateVars));</code>
By invoking this function, you can generate the desired string while possessing the flexibility to modify variables at runtime.
Benefits of this approach:
Potential drawbacks:
In summary, while ES6 template literals inherently lack true reusability, employing the Function constructor offers a workaround that emulates the desired behavior of creating and modifying templates at runtime.
The above is the detailed content of Can ES6 Template Literals be Truly Reusable?. For more information, please follow other related articles on the PHP Chinese website!