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

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

问题描述

我正在使用新的 ES6 Template Literals 功能和第一件事我想到的是 JavaScript 的 String.format 所以我开始实现一个原型:

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:

  • 使用模板字符串,就像它们设计的那样,没有任何format函数:

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"));
    

  • 使用标记的模板文字.请注意,替换仍将在没有处理程序拦截的情况下进行评估,因此您不能在没有名为 so 的变量的情况下使用像 p0 这样的标识符.如果不同的替换正文语法 提议被接受(更新:不是).

  • 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天全站免登陆