调用函数的反引号 [英] Backticks calling a function

查看:381
本文介绍了调用函数的反引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

  console.log`1` 

在Google Chrome中,我输出如

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

为什么回调函数调用日志功能,为什么它的索引为$ code raw:Array [1] ?



由Catgocat在JS房间里提出的问题,但除了

p>在ES-6中称为标签模板字符串可以更多地阅读关于它们的这里有趣的是,我发现在聊天的主演部分中的链接。



但是鳕鱼的相关部分e在下面(你基本可以创建一个过滤器排序)。

 函数标签(strings,... values){
assert(strings [0] ==='a');
assert(strings [1] ==='b');
assert(values [0] === 42);
return'whatever';
}
标签`a $ {42} b` //whatever

基本上它只是使用console.log函数标记1,就像它对任何其他函数一样。标签功能接受模板字符串的解析值和分别执行进一步任务的值。



Babel将上述代码转移到

  var _taggedTemplateLiteralLoose = function(strings,raw){strings.raw = raw;返回字符串; }; 

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

正如你在上面的例子中看到的那样,在被babel玷污之后,标签功能(控制台.log)正在传递以下es6-> 5个转化代码的返回值。



_taggedTemplateLiteralLoose([1],[1]);



此函数的返回值传递给console.log,然后打印该数组。


I'm not sure how to explain this, but when I run

console.log`1`

In google chrome, I get output like

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

Why is the backtick calling the log function, and why is it making a index of raw: Array[1]?

Question brought up in the JS room by Catgocat, but no answers made sense besides something about templating strings that didn't really fit why this is happening.

解决方案

It is called Tagged Template String in ES-6 more could be read about them Here, funny I found the link in the starred section of the very chat.

But the relevent part of the code is below (you can basically create a filter sort).

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

Basically its merely tagging the "1" with console.log function, as it would do with any other function. The tagging functions accept parsed values of template strings and the values seperately upon which further tasks can be performed.

Babel transpiles the above code to

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

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

As you can see it in the example above, after being transpiled by babel, the tagging function (console.log) is being passed the return value of the following es6->5 transpiled code.

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

The return value of this function is passed to console.log which will then print the array.

这篇关于调用函数的反引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆