【问题标题】:Backticks calling a function反引号调用函数
【发布时间】:2015-06-22 00:19:11
【问题描述】:

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

console.log`1`

在谷歌浏览器中,我得到类似的输出

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

为什么反引号会调用日志函数,为什么索引为raw: Array[1]

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

【问题讨论】:

标签: javascript ecmascript-6 template-strings template-literals tagged-templates


【解决方案1】:

迟到了,但是,TBH,没有一个答案能解释 50% 的原始问题(“为什么raw: Array[1]”)

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

console.log`1`

正如其他人所指出的,这被称为Tagged Template(更多详细信息还有here)。

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

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

基本上,以下是“几乎”等价的

// 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"]

【讨论】:

    【解决方案2】:

    它在 ES-6 中被称为标记模板,可以阅读更多关于它们的信息Here有趣的是,我在聊天的星号部分找到了链接。

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

    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 转译代码的返回值。

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

    这个函数的返回值被传递给console.log然后打印数组。

    【讨论】:

    【解决方案3】:

    标记模板文字:

    以下语法:

    function`your template ${foo}`;
    

    称为标记模板文字。


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

    function taggedTemplate(strings, arg1, arg2, arg3, arg4) {
      console.log(strings);
      console.log(arg1, arg2, arg3, arg4);
    }
    
    taggedTemplate`a${1}b${2}c${3}`;
    1. 第一个参数是所有单个字符串字符的数组
    2. 剩余的参数对应于我们通过字符串插值接收的变量值。请注意,在示例中 arg4 没有值(因为只有 3 次字符串插值),因此当我们尝试记录 arg4 时会记录 undefined

    使用rest参数语法:

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

    function taggedTemplate(strings, ...rest) {
      console.log(rest);
    }
    
    taggedTemplate `a${1}b${2}c${3}`;
    taggedTemplate `a${1}b${2}c${3}d${4}`;

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      • 2018-12-27
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多