这个概念我也不知道怎么解释,还是直接看规范给出的描述吧,在12.3.7章节:
A tagged template is a function call where the arguments of the call are derived from a TemplateLiteral (12.2.9). The actual arguments include a template object (12.2.9.3) and the values produced by evaluating the expressions embedded within the TemplateLiteral.
先看个简单的例子:
function foo(strings, ...values) {
console.log( strings );
console.log( values );
}
var desc = "awesome";
foo`Everything is ${desc}!`;
// [ "Everything is ", "!"]
// [ "awesome" ]
这个语法就是一个函数调用,前面的foo是个函数,形参是template literal,实参的第一个参数是个数组对象,数组个数是template中变量个数加1,也就是说数组的元素相当于用split函数分割了模板,如下:
"Everything is ${}!${}".split(/\$\{[^\}]*\}/)//["Everything is ", "!", ""]
其实第一个参数中还有个属性叫raw,如果们console.log(strings.raw),也能打印出一个数组,这个数组中的元素相当于每个都是用String.raw处理过一样,上篇文章中我们讲到过这种用法。
函数的第二个实参相当于template中变量的实际值,上面用rest操作符做了处理。
这样解释完了,应该对这个特性有点了解了吧。下面看个简单应用,格式化货币的小数位:
function dollabillsyall(strings, ...values) {
return strings.reduce( function(s,v,idx){
if (idx > 0) {
if (typeof values[idx-1] == "number") {
s += `$${values[idx-1].toFixed( 2 )}`;
//s += "$" + values[idx-1].toFixed( 2 );
}
else {
s += values[idx-1];
}
}
return s + v;
}, "" );
}
var amt1 = 11.99,
amt2 = amt1 * 1.08,
name = "Kyle";
var text = dollabillsyall
`Thanks for your purchase, ${name}! Your
product cost was ${amt1}, which with tax
comes out to ${amt2}.`
console.log( text );
Thanks for your purchase, Kyle! Your
product cost was $11.99, which with tax
comes out to $12.95.
再看一个mozilla上的例子:
function template(strings, ...keys) {
return (function(...values) {
var dict = values[values.length - 1] || {};
var result = [strings[0]];
keys.forEach(function(key, i) {
var value = Number.isInteger(key) ? values[key] : dict[key];
result.push(value, strings[i + 1]);
});
return result.join('');
});
}
template`${0}${1}${0}!`('Y', 'A'); // "YAY!"
template`${0} ${'foo'}!`('Hello', {foo: 'World'}); // "Hello World!"
上面这个用法更高级一点,template函数本身返回了一个函数,然后执行,去替换模板中的索引变量。
如果template literal前面不是函数会怎么样?报错
var aaa = 1;
aaa `Hello World!`//TypeError: aaa is not a function
*以上全部代码在Firefox 43下通过测试