Sub topic 11
Member Tags, this Binding, and Chained Tags
This chapter assumes you already know how a tag receives its strings array and its values, and that you know how this works for ordinary method calls in JavaScript. So far, the tag has always been a plain identifier such as html or sql. The grammar is looser than that. A tag can be any member expression or call expression, and the kind of expression you use decides what this is inside the tag.
Member Tags Are Method Calls
If the tag is a property access, such as obj.tag or obj['tag'], JavaScript calls it as a method. Inside the function, this is the object that owns the property, just as in obj.tag(...).
const formatter = {
prefix: '[log] ',
tag(strings, ...values) {
return this.prefix + String.raw(strings, ...values);
},
};
console.log(formatter.tag`count=${3}`); // '[log] count=3'
console.log(formatter['tag']`count=${4}`); // '[log] count=4'Evaluation follows a fixed order. JavaScript first evaluates the tag expression and records its base object. Next it evaluates the substitutions from left to right. Last, it calls the function.
Losing this When You Detach a Tag
People often pull a method out into a variable so the tag reads more cleanly. Doing that drops the base object. In a module or in strict code, this is then undefined.
'use strict';
const formatter = {
prefix: '[log] ',
tag(strings, ...values) {
return this.prefix + String.raw(strings, ...values);
},
};
const log = formatter.tag;
try {
log`count=${3}`;
} catch (e) {
console.log(e instanceof TypeError); // true: cannot read 'prefix' of undefined
}
const boundLog = formatter.tag.bind(formatter);
console.log(boundLog`count=${3}`); // '[log] count=3'The fixes are the same ones you would use for any method. You can call the tag through the object, bind it, or write the tag as a closure that never reads this.
Call Expressions as Tags: Tag Factories
A call expression can also be a tag, so make(options) followed by a template is valid. The call runs first, and whatever function it returns becomes the tag. Libraries use this form to configure a tag before it runs. styled-components' styled(Button) followed by a template is one example.
function joinWith(separator) {
return (strings, ...values) =>
strings.reduce((out, str, i) => out + separator + values[i - 1] + separator + str);
}
console.log(joinWith('|')`a${1}b${2}c`); // 'a|1|b|2|c'Chained Tags
A tagged template is itself a member-level expression, so you can put another template straight after it. `taga`b ` parses as (taga)b `. This works only if the first tag returns a function.
function collect(strings, ...values) {
const parts = [String.raw(strings, ...values)];
const next = (s, ...v) => {
parts.push(String.raw(s, ...v));
return next;
};
next.done = () => parts.join(' ');
return next;
}
console.log(collect`a``b${1}``c`.done()); // 'a b1 c'| Tag form | Example | `this` inside the tag |
|---|---|---|
| Identifier | ``tag`x` `` | `undefined` in strict mode |
| Member | ``obj.tag`x` `` | `obj` |
| Call (factory) | ``make(opts)`x` `` | depends on the returned function |
| Chained | ``tag`a``b` `` | `undefined` for the second call |
In the chained form, the second template calls the returned function with no base object. That is why collect uses a closure for its state and does not rely on this.
Exercise
Given const o = { n: 5, t(s) { return this.n; } };, what do o.tx` and (0, o.t)x` return in strict mode?
Show answer
o.tx` returns 5 because the member tag is called with this set to o. (0, o.t)x throws a TypeError. The comma expression returns the bare function, so it is called with this as undefined, and reading this.n` fails.
Exercise
Why does `joinWith('-')x${1}y work, while joinWithx${1}y ` does not produce a joined string?
Show answer
In the first form, joinWith('-') runs first and returns a tag function, which then receives the template. In the second form, joinWith itself is the tag. It receives the strings array as separator and returns a function instead of a string.