我正在玩新的 ES6 Template Literals特性,我首先想到的是 JavaScript 的 String.format
,所以我着手实现一个原型(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"));
但是,模板文字在传递到我的原型(prototype)方法之前被求值。有什么方法可以编写上述代码来将结果推迟到我动态创建元素之后?
最佳答案
我可以看到三种解决方法:
按照设计目的使用模板字符串,无需任何
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}`);
甚至函数参数用于实际延迟评估:
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
这样的标识符。如果 different substitution body syntax proposal is accepted,此行为可能会改变(更新:不是)。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: ^ ^
关于javascript - 延迟执行 ES6 模板文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22607806/