【问题标题】:Why do template strings (``) execute preceding token as a function? [duplicate]为什么模板字符串 (``) 将前面的标记作为函数执行? [复制]
【发布时间】:2017-04-23 23:54:29
【问题描述】:

我今天遇到了一个错误 - TypeError: "fa" is not a function - 经过短暂的调查,我找到了原因。我忘记了对象文字中的逗号,这给我留下了相当于一个字符串,后跟一个模板字符串,基本上是:"fa"``。看到 not a function 后,我预计会找到一些冒犯性的括号,并觉得这很好奇,所以我在 Node REPL 中加深了我的调查。

''``               // TypeError: '' is not a function
'foo'``            // TypeError: 'foo' is not a function
1``                // TypeError: 1 is not a function
(() => 'foobar')`` //'foobar'

好的,所以我发现模板字符串的工作方式类似于在标记后放置括号。越来越好奇。

我想知道它是否传递了任何参数,所以我写了这个:

function showArgs () {
  return arguments
}

showArgs()                  // {}
showArgs``                  // { '0': [ '' ] }
showArgs`foo`               // { '0': [ 'foo' ] }
showArgs`foo${'bar'}`       // { '0': [ 'foo', '' ], '1': 'bar' }
showArgs`foo${'bar'}${1}`   // { '0': [ 'foo', '', '' ], '1': 'bar', '2': 1 }
showArgs(`foo${'bar'}${1}`) // { '0': 'foobar1`' }

这是怎么回事?

参数显然与模板字符串有关,因为它们可用于通过将第 n 个数组项与第 n + 1 个连接来构造它参数并将它们全部连接起来,但是为什么模板字符串使用这些参数执行前面的标记?

【问题讨论】:

标签: javascript function ecmascript-6 template-strings


【解决方案1】:

查看tagged template literals

模板文字的更高级形式是标记模板文字。使用它们,您可以使用函数修改模板文字的输出。第一个参数包含一个字符串字面量数组 [...]。第二个,以及第一个之后的每个参数,是处理的(或有时称为cooked)替换表达式的值[...]。最后,您的函数返回您操作的字符串。


来自 MDN 的示例:

var a = 5;
var b = 10;

function tag(strings, ...values) {
  console.log(strings[0]); // "Hello "
  console.log(strings[1]); // " world "
  console.log(strings[2]); // ""
  console.log(values[0]);  // 15
  console.log(values[1]);  // 50

  return "Bazinga!";
}

tag`Hello ${ a + b } world ${ a * b }`;
// "Bazinga!"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 2014-02-08
    • 1970-01-01
    • 2010-12-22
    • 1970-01-01
    • 2013-09-20
    • 1970-01-01
    相关资源
    最近更新 更多