如何使用函数或变量重用模板文字?

时间:2018-12-14 18:24:28

标签: javascript ecmascript-6 template-literals

在初始表达/赋值之后,是否可以继续使用模板?

如预期的那样,它起作用:

const testTag = (strings, ...values) => console.log(strings, values);
testTag `${'this'}${'is'}${'test'}`;
> ["", "", "", ""], raw: ["", "", "", ""]
> ["this", "is", "test"]

这不是:

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteral = `${'this'}${'is'}${'test'}`;
testTag testLiteral;
> Uncaught SyntaxError: Unexpected identifier

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteral = `${'this'}${'is'}${'test'}`;
testTag `${testLiteral}`;
> ["", ""], raw: ["", ""]
> ["thisistest"]

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteralMaker = () => `${'this'}${'is'}${'test'}`;
testTag `${testLiteralMaker()}`;
> ["", ""], raw: ["", ""]
> ["thisistest"]

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteralMaker = () => `${'this'}${'is'}${'test'}`;
testTag(testLiteralMaker());
> thisistest
> []

const testTag = (strings, ...values) => console.log(strings, values);
const testLiteralMaker = () => `${'this'}${'is'}${'test'}`;
testTag(...testLiteralMaker());
> t
> ["h", "i", "s", "i", "s", "t", "e", "s", "t"]

((strings, ...values) => console.log(strings, values))(`${'this'}${'is'}${'test'}`)
> thisistest
> []

((strings, ...values) => console.log(strings, values))((() => `${'this'}${'is'}${'test'}`)())
> thisistest
> []

我对我可以使用模板文字编写可重用代码的方式很感兴趣,但是我无法理解两个函数如何有意义地共享它们。

0 个答案:

没有答案