Sub topic 11
Member Tags, this Binding, and Chained Tags
So far the tags in this tutorial have been plain identifiers such as html or sql. The grammar allows more than that. The thing before the backtick can be any member expression: a property access, a computed property, a function call that returns a tag, or even another tagged template. This chapter covers what each form means, what this is inside the tag, the order in which the parts are evaluated, and the forms the parser rejects.
This chapter assumes you know how a tag receives (strings, ...values), how String.raw joins parts, and how this works for ordinary method calls.
What Can Appear Before the Backtick
The specification defines a tagged template as a MemberExpression followed by a template literal. In practice, the tag can be any of the following:
| Tag form | Example | What gets called |
|---|---|---|
| Identifier | `` html`...` `` | The function bound to `html` |
| Property access | `` styled.div`...` `` | The `div` property of `styled`, as a method |
| Computed property | `` obj['tag']`...` `` | The property named by the expression, as a method |
| Call result | `` currency('EUR')`...` `` | Whatever function `currency('EUR')` returns |
| Tagged template result | `` tag`a``b` `` | Whatever `` tag`a` `` returns, called with the second template |
| Parenthesized expression | `` (cond ? a : b)`...` `` | Whatever the expression evaluates to |
The tagged template also binds as tightly as a call, so whatever follows it applies to the tag's return value. ` html<p>x</p>.trim() calls trim` on the result of the tag, not on the template.
Member Tags and the this Binding
A tagged template follows the same rule as a normal call. If the tag is a property reference, the function is called as a method and this is the object that owns the property. ` obj.tagx behaves like obj.tag(strings, 'x'...) with respect to this`.
class Logger {
constructor(prefix) {
this.prefix = prefix;
}
tag(strings, ...values) {
return this.prefix + String.raw(strings, ...values);
}
}
const log = new Logger('[app] ');
console.log(log.tag`ready=${true}`); // '[app] ready=true'
console.log(log['tag']`port=${8080}`); // '[app] port=8080'
console.log((log.tag)`grouped`); // '[app] grouped'The computed form log['tag'] is a property reference too, so it also gets this === log. Wrapping the reference in plain parentheses, as in (log.tag), does not change anything. The parentheses group the expression, but the reference to the property remains intact, the same way (log.tag)() still calls a method.
Losing this
The binding goes away as soon as the function is read out of the object into a plain value. It goes away when you assign it to a variable, destructure it, or pass it through the comma operator.
class Logger {
constructor(prefix) {
this.prefix = prefix;
}
tag(strings, ...values) {
return this.prefix + String.raw(strings, ...values);
}
}
const log = new Logger('[app] ');
const detached = log.tag;
try {
detached`lost`;
} catch (e) {
console.log(e instanceof TypeError); // true: this is undefined (class bodies are strict)
}
try {
(0, log.tag)`also lost`;
} catch (e) {
console.log(e instanceof TypeError); // true: the comma operator yields a plain value
}
const bound = log.tag.bind(log);
console.log(bound`kept`); // '[app] kept'In sloppy-mode code outside a class, a detached tag gets globalThis as this and does not throw. In that case this.prefix is usually undefined and you get output like 'undefinedlost'. That failure is quieter and harder to spot than the TypeError.
Fixes for Detached Tags
There are three common ways to make a tag work no matter how it is referenced:
- Bind it once:
this.tag = this.tag.bind(this)in the constructor. - Define it as an arrow-function class field, which captures
thislexically. - Do not use
thisat all: close over the state the tag needs.
class Logger {
constructor(prefix) {
this.prefix = prefix;
}
tag = (strings, ...values) => this.prefix + String.raw(strings, ...values);
}
const { tag } = new Logger('[svc] ');
console.log(tag`destructured and still works`); // '[svc] destructured and still works'The third option is the most common one in libraries, and the next section shows it.
Tag Factories: Calling a Function That Returns a Tag
A call result can be the tag, so a function can take configuration and return a tag. The syntax ` currency('EUR')... ` is two calls in a row: the first builds the tag and the second applies it to the template.
function currency(code) {
const fmt = new Intl.NumberFormat('en-US', { style: 'currency', currency: code });
return (strings, ...values) =>
strings.reduce((out, str, i) => out + fmt.format(values[i - 1]) + str);
}
console.log(currency('EUR')`Total: ${12.5}`); // 'Total: €12.50'
const usd = currency('USD');
console.log(usd`Price ${3} and tax ${0.24}`); // 'Price $3.00 and tax $0.24'The factory pattern avoids the this problem entirely because the tag closes over fmt. It also lets you build the expensive formatter once and reuse it. styled-components uses both forms: styled.div is a member tag, and styled(Button) is a factory call that returns a tag. Both are followed directly by a template.
Chained Tags
Because the result of a tagged template is itself a valid tag expression, you can write several templates in a row. ` taga`b ` parses as (taga)b . The first call must return a function, or the second call throws a TypeError`.
function words(strings, ...values) {
const parts = [String.raw(strings, ...values)];
const next = (s, ...v) => {
parts.push(String.raw(s, ...v));
return next;
};
next.toString = () => parts.join(' ');
return next;
}
const n = 3;
console.log(String(words`one``two``${n} three`)); // 'one two 3 three'Chaining works, but real code rarely uses it because readers often take ` a`b ` for a typo. Its main use is in small builder DSLs where each template adds one piece. If you design an API like this, document it clearly and think about whether a factory call such as tag(options)... ` would be easier to read.
Evaluation Order
The steps of a tagged template run in a fixed order:
- Evaluate the tag expression, including any property lookups or factory calls.
- Evaluate each substitution from left to right.
- Check that the tag value is callable, then call it.
The callable check comes last, so the substitutions run even when the tag is not a function. If those expressions have side effects, the side effects happen before the error.
const trace = [];
function getTag() {
trace.push('tag');
return (strings, ...values) => {
trace.push('call');
return values;
};
}
function val(x) {
trace.push('value ' + x);
return x;
}
getTag()`${val(1)} ${val(2)}`;
console.log(trace); // [ 'tag', 'value 1', 'value 2', 'call' ]
trace.length = 0;
const notATag = 5;
try {
notATag`${val(3)}`;
} catch (e) {
console.log(trace, e instanceof TypeError); // [ 'value 3' ] true
}Forms the Parser Rejects
You cannot use optional chaining with a tagged template. ` obj?.tagx and obj?.a.bx are early SyntaxError`s, so the whole script fails to load and no code runs. The language rejects them because no sensible result exists when the chain short-circuits.
try {
new Function('obj', 'return obj?.tag`x`');
} catch (e) {
console.log(e.name); // 'SyntaxError'
}
const maybe = undefined;
const result = maybe?.tag ? maybe.tag`x` : undefined;
console.log(result); // undefinedWrite the check explicitly, as shown in the last lines of the example.
Exercise
Given const o = { p: '>', t(s, ...v) { return this.p + String.raw(s, ...v); } };, what do ` o.tx , (o.t)x , and (0, o.t)x ` produce in strict mode?
Show answer
` o.tx returns '>x' because the member tag gets this === o. (o.t)x also returns '>x' because plain parentheses keep the property reference. (0, o.t)x ` throws a TypeError because the comma operator yields a bare function value, so this is undefined and reading this.p fails.
Exercise
In ` let n = 0; const t = null; try { t${n++}${n++} } catch {} `, what is n afterward, and why?
Show answer
n is 2. The tag expression is evaluated first, then both substitutions run left to right, and only then does JavaScript check whether t is callable and throw a TypeError. The increments have already happened by that point.
Exercise
Write a factory prefixed(p) that returns a tag, so that ` prefixed('> ')a=${1} returns '> a=1'. The returned tag must still work after const { tag } = { tag: prefixed('# ') }`.
Show answer
const prefixed = (p) => (strings, ...values) => p + String.raw(strings, ...values); The tag closes over p and never reads this, so it keeps working after destructuring: ` tagb=${2} ` returns '# b=2'.