ES6 tagged templates practical usability

前端 未结 3 2058
时光取名叫无心
时光取名叫无心 2020-11-27 21:24

I understand the syntax of ES6 tagged templates. What I don\'t see is the practical usability. When is it better than passing an object parameter, like the settings in jQuer

3条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 21:39

    See Sitepoint's explanation:

    The final stage of template strings specification is about adding a custom function before the string itself to create a tagged template string.

    ...

    For instance, here is a piece of code to block strings that try to inject custom DOM elements:

    var items = [];
    items.push("banana");
    items.push("tomato");
    items.push("light saber");
    var total = "Trying to hijack your site 
    "; var myTagFunction = function (strings,...values) { var output = ""; for (var index = 0; index < values.length; index++) { var valueString = values[index].toString(); if (valueString.indexOf(">") !== -1) { // Far more complex tests can be implemented here :) return "String analyzed and refused!"; } output += strings[index] + values[index]; } output += strings[index] return output; } result.innerHTML = myTagFunction `You have ${items.length} item(s) in your basket for a total of $${total}`;

    Tagged template strings can used for a lot of things like security, localization, creating your own domain specific language, etc.

提交回复
热议问题