延迟ES6模板文字的执行 [英] Defer execution for ES6 Template Literals

查看:113
本文介绍了延迟ES6模板文字的执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用新的 ES6模板文字功能,第一件事来到我的头是一个 String.format 为Javascript,所以我去实现一个原型:

I am playing with the new ES6 Template Literals feature and the first thing that came to my head was a String.format for Javascript so I went about implementing a prototype:

String.prototype.format = function() {
  var self = this;
  arguments.forEach(function(val,idx) {
    self["p"+idx] = val;
  });
  return this.toString();
};
console.log(`Hello, ${p0}. This is a ${p1}`.format("world", "test"));

ES6Fiddle

但是,在将传递给我的原型方法之前,模板文字被评估。有没有办法写上面的代码推迟结果,直到我动态创建元素?

However, the Template Literal is evaluated before it's passed to my prototype method. Is there any way I can write the above code to defer the result until after I have dynamically created the elements?

推荐答案

我可以请参阅以下三种方式:

I can see three ways around this:


  • 使用设计为使用的模板字符串,而不需要任何格式 function:

  • Use template strings like they were designed to be used, without any format function:

console.log(`Hello, ${"world"}. This is a ${"test"}`);
// might make more sense with variables:
var p0 = "world", p1 = "test";
console.log(`Hello, ${p0}. This is a ${p1}`);
// or even function parameters for actual deferral of the evaluation:
const welcome = (p0, p1) => `Hello, ${p0}. This is a ${p1}`;
console.log(welcome("world", "test"));


  • 不要使用模板字符串,而是使用纯字符串文字:

  • Don't use a template string, but a plain string literal:

    String.prototype.format = function() {
        var args = arguments;
        return this.replace(/\$\{p(\d)\}/g, function(match, id) {
            return args[id];
        });
    };
    console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));
    


  • 使用标记的模板文字。请注意,替换仍将被处理程序进行评估,而不会使用 p0 之类的标识符,而不使用名为so的变量。 如果不同的替代主体语法提案是,则此行为可能会更改接受(更新:不是)。

  • Use a tagged template literal. Notice that the substitutions will still be evaluated without interception by the handler, so you cannot use identifiers like p0 without having a variable named so. This behavior may change if a different substitution body syntax proposal is accepted (Update: it was not).

    function formatter(literals, ...substitutions) {
        return {
            format: function() {
                var out = [];
                for(var i=0, k=0; i < literals.length; i++) {
                    out[k++] = literals[i];
                    out[k++] = arguments[substitutions[i]];
                }
                out[k] = literals[i];
                return out.join("");
            }
        };
    }
    console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));
    // Notice the number literals: ^               ^
    


  • 这篇关于延迟ES6模板文字的执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆