为了账号安全,请及时绑定邮箱和手机立即绑定

推迟执行ES6模板文字

推迟执行ES6模板文字

繁华开满天机 2019-10-10 16:14:24
我正在使用新的ES6模板文字功能,想到的第一件事是String.formatJavaScript,因此我着手实现了一个原型: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"));ES6提琴但是,在将模板文字传递给我的原型方法之前,需要先对其进行评估。有什么方法可以编写上述代码以将结果推迟到动态创建元素之后?
查看完整描述

3 回答

?
守着一只汪

TA贡献1872条经验 获得超3个赞

我可以看到三种解决方法:


使用模板字符串,就像设计使用的那样,没有任何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"));

不要使用模板字符串,而应使用纯文本字符串:


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 那样使用标识符。如果接受其他替换主体语法建议,此行为可能会更改(更新:否)。


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: ^               ^


查看完整回答
反对 回复 2019-10-10
?
catspeake

TA贡献1111条经验 获得超0个赞

AFAIS,有用的功能“延迟执行字符串模板”仍然不可用。但是,使用lambda是一种表达力强,易读且简短的解决方案:


var greetingTmpl = (...p)=>`Hello, ${p[0]}. This is a ${p[1]}`;


console.log( greetingTmpl("world","test") );

console.log( greetingTmpl("@CodingIntrigue","try") );


查看完整回答
反对 回复 2019-10-10
  • 3 回答
  • 0 关注
  • 262 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信