猿问

推迟执行ES6模板文字

我正在使用新的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提琴


但是,在将模板文字传递给我的原型方法之前,需要先对其进行评估。有什么方法可以编写上述代码以将结果推迟到动态创建元素之后?


繁华开满天机
浏览 263回答 3
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() {&nbsp; &nbsp; var args = arguments;&nbsp; &nbsp; return this.replace(/\$\{p(\d)\}/g, function(match, id) {&nbsp; &nbsp; &nbsp; &nbsp; return args[id];&nbsp; &nbsp; });};console.log("Hello, ${p0}. This is a ${p1}".format("world", "test"));使用带标签的模板文字。请注意,替换仍将在不被处理程序拦截的情况下进行求值,因此您不能像p0没有变量so 那样使用标识符。如果接受其他替换主体语法建议,此行为可能会更改(更新:否)。function formatter(literals, ...substitutions) {&nbsp; &nbsp; return {&nbsp; &nbsp; &nbsp; &nbsp; format: function() {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var out = [];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; for(var i=0, k=0; i < literals.length; i++) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out[k++] = literals[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out[k++] = arguments[substitutions[i]];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; out[k] = literals[i];&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; return out.join("");&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; };}console.log(formatter`Hello, ${0}. This is a ${1}`.format("world", "test"));// Notice the number literals: ^&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;^

catspeake

AFAIS,有用的功能“延迟执行字符串模板”仍然不可用。但是,使用lambda是一种表达力强,易读且简短的解决方案:var greetingTmpl = (...p)=>`Hello, ${p[0]}. This is a ${p[1]}`;console.log( greetingTmpl("world","test") );console.log( greetingTmpl("@CodingIntrigue","try") );
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答