反引号 (`...`) 在 JavaScript 中调用函数

Backticks (`…`) calling a function in JavaScript

我不知道该如何解释,但是当我 运行

console.log`1`

在 google chrome 中,我得到类似

的输出
console.log`1`
VM12380:2 ["1", raw: Array[1]]

为什么反引号会调用log函数,为什么会做raw: Array[1]的索引?

Catgocat 在 JS 室中提出的问题,但除了关于 templating strings 的某些内容与发生这种情况的原因不符外,没有任何答案有意义。

它在 ES-6 中被称为标记模板更多可以阅读 Here有趣的是我在聊天的加星标部分找到了 link。

但代码的相关部分如下(您基本上可以创建过滤排序)。

function tag(strings, ...values) {
  assert(strings[0] === 'a');
  assert(strings[1] === 'b');
  assert(values[0] === 42);
  return 'whatever';
}
tag `a${ 42 }b`  // "whatever"

基本上,它只是用 console.log 函数标记“1”,就像它对任何其他函数所做的那样。标记函数接受模板字符串的解析值和可以执行进一步任务的值。

Babel 将上述代码转译为

var _taggedTemplateLiteralLoose = function (strings, raw) { strings.raw = raw; return strings; };

console.log(_taggedTemplateLiteralLoose(["1"], ["1"]));

正如你在上面的例子中看到的那样,在被 babel 转译后,标记函数 (console.log) 被传递给以下 es6->5 转译代码的 return 值.

_taggedTemplateLiteralLoose( ["1"], ["1"] );

此函数的 return 值被传递给 console.log,然后它将打印数组。

标记的模板文字:

语法如下:

function`your template ${foo}`;

被称为标记的模板文字。


作为标记模板文字调用的函数以下列方式接收其参数:

function taggedTemplate(strings, arg1, arg2, arg3, arg4) {
  console.log(strings);
  console.log(arg1, arg2, arg3, arg4);
}

taggedTemplate`abc`;

  1. 第一个参数是所有单个字符串字符的数组
  2. 剩下的参数对应于我们通过字符串插值接收到的变量值。请注意示例中 arg4 没有值(因为只有 3 次字符串插值)因此当我们尝试记录 arg4
  3. 时会记录 undefined

使用剩余参数语法:

如果我们事先不知道在模板字符串中将发生多少次字符串插值,使用剩余参数语法通常很有用。此语法将函数接收的剩余参数存储到数组中。例如:

function taggedTemplate(strings, ...rest) {
  console.log(rest);
}

taggedTemplate `abc`;
taggedTemplate `abcd`;

晚会迟到了,但是,TBH,none 的答案解释了原始问题的 50%(“为什么 raw: Array[1]”)

1。为什么可以使用反引号调用不带括号的函数?

console.log`1`

正如其他人指出的那样,这称为 Tagged Template (more details also here)。

使用此语法,该函数将接收以下参数:

  • 第一个参数:一个数组,包含字符串中不是表达式的不同部分。
  • 其余参数:每个被插值的值(即那些是表达式的值)。

基本上,以下是'almost'等价

// Tagged Template
fn`My uncle ${uncleName} is ${uncleAge} years old!`
// function call
fn(["My uncle ", " is ", " years old!"], uncleName, uncleAge);

(请参阅第 2 点以了解为什么它们不完全相同)

2。为什么 ["1", raw: Array[1]] ???

作为第一个参数传递的数组包含 属性 raw,它允许 accessing the raw strings 输入(不处理转义序列)。

示例用例:

let fileName = "asdf";

fn`In the folder C:\Documents\Foo, create a new file ${fileName}`

function fn(a, ...rest) {
  console.log(a); //In the folder C:DocumentsFoo, create a new file
  console.log(a.raw); //In the folder C:\Documents\Foo, create a new file 
}

什么,一个带有属性的数组??? ???

是的,因为 JavaScript 数组实际上是对象,所以它们可以 store properties

示例:

const arr = [1, 2, 3];
arr.property = "value";
console.log(arr); //[1, 2, 3, property: "value"]