Backticks calling a function

2019-01-01 01:07发布

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.

2条回答
骚的不知所云
2楼-- · 2019-01-01 01:37

It is called Tagged Template 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 relevant part of the code is below (you can basically create a filtered 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 separately 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.

查看更多
刘海飞了
3楼-- · 2019-01-01 01:49

Tagged template literal:

The following syntax:

function`your template ${foo}`;

Is called the tagged template literal.


The function which is called as a tagged template literal receives the its arguments in the following manner:

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

taggedTemplate`a${1}b${2}c${3}`;

  1. The first argument is an array of all the individual string characters
  2. The remaining argument correspond with the values of the variables which we receive via string interpolation. Notice in the example that there is no value for arg4 (because there are only 3 times string interpolation) and thus undefined is logged when we try to log arg4

Using the rest parameter syntax:

If we don't know beforehand how many times string interpolation will take place in the template string it is often useful to use the rest parameter syntax. This syntax stores the remaining arguments which the function receives into an array. For example:

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

taggedTemplate `a${1}b${2}c${3}`;
taggedTemplate `a${1}b${2}c${3}d${4}`;

查看更多
登录 后发表回答