具有模板文字但不带括号的ES6调用函数 [英] ES6 calling function with template literal but no parentheses

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

问题描述

根据MDN,标记的模板文字可以如下使用:

According to MDN, Tagged template literals can be used as follows:

var a = 5;
var b = 10;
function tag(strings, ...values) {
  alert(strings[0]); // "Hello "
  alert(strings[1]); // " world "
  alert(values[0]); // 15
  alert(values[1]); // 50
  return "Bazinga!";
}
tag `Hello ${ a + b } world ${ a * b }`; // "Bazinga!"

在上面的示例中,在不使用括号的情况下调用了函数tag.

In the example above, the function tag is called without using parentheses.

我希望它应该像tag(`Hello`)那样被调用,但是它将模板文字产生的字符串作为函数的strings参数的参数传递.

I expected it should be called like tag(`Hello`), but that passes the string resulting from the template literal as the argument for the strings parameter of the function.

不带括号但带有参数的调用函数的特殊功能是什么?

What's this special feature of calling functions without parentheses but with parameter?

推荐答案

不带括号的调用函数的特殊功能是什么?

What's this special feature of calling functions without parentheses?

此标记模板的语法仅语法允许:

MemberExpression : MemberExpression TemplateLiteral
CallExpression : CallExpression TemplateLiteral

这些规则意味着将MemberExpressionCallExpression后跟TemplateLiteral的内容视为函数调用.规范中的附加说明:

These rules means that a MemberExpression or CallExpression followed by a TemplateLiteral is considered to be a function call. Additional note from the spec:

带标签的模板是一个函数调用,其中调用的参数来自TemplateLiteral( 12.2.9.3 ),以及通过评估嵌入在TemplateLiteral中的表达式而产生的值.

A tagged template is a function call where the arguments of the call are derived from a TemplateLiteral (12.2.9). The actual arguments include a template object (12.2.9.3) and the values produced by evaluating the expressions embedded within the TemplateLiteral.

如果您要问为什么这样做,我无法给您答案.

If you are asking for why it was done this way, I cannot give you an answer.

但是,如果考虑一下,就不可能只使用普通"函数调用语法. tag(`...`)表示为tag传递了一个参数,即评估模板文字的结果.但是正如您在MDN的示例中所看到的那样,带标签的模板函数实际上会传递多个参数.如果通过模板文字传递的函数(内部)以不同的方式调用(而不是以不同的值调用),那肯定会更加令人惊讶.然后,如果您真的想将模板文字传递给该函数,该如何调用呢?

However, if you think about it, the couldn't have just used "ordinary" function call syntax. tag(`...`) means that tag is passed a single argument, the result of evaluating the template literal. But as you can see in the example from MDN, tagged template functions actually get passed multiple arguments. It would certainly be more surprising if functions were called differently (internally) if they were passed a template literal vs if they were called with a different value. And then, how would call a function if you really wanted to pass a template literal to it?

因此引入一种新语法似乎很有意义.

Hence introducing a new syntax seems to make sense.

FWIW,这是的语法普通"函数调用:

CallExpression : MemberExpression Arguments
CallExpression : CallExpression Arguments

这篇关于具有模板文字但不带括号的ES6调用函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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