为什么在使用模板字符串时可以在没有括号的情况下调用函数? [英] Why can functions be called without parentheses when using template strings?

查看:402
本文介绍了为什么在使用模板字符串时可以在没有括号的情况下调用函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个简单的日志记录功能:

I have a simple logging function:

function log(str) {
  console.log('logged: ', str);
}

如果我在没有括号的情况下调用它(目前使用Chrome的开发工具)并传入一个模板字符串,如下所示:

If I call it without parentheses (currently using Chrome's dev tools) and pass in a template string, like this:

log`foo`

输出为:已记录:[foo,raw:Array [1]]

如果我用括号称呼它,

log(`foo`)

输出为:已记录:foo

为什么在Javascript中使用模板字符串调用函数没有括号?发生什么导致结果与用括号调用结果不同?

Why does calling a function using a template string an no parentheses work in Javascript? What is happening that causes the result to be different from calling it with parentheses?

推荐答案

第一个例子( log`foo` )允许语言规范确定传递给日志函数的值(参见 12.3.7 )。第二个例子( log(`foo`))显式传递一个参数。

The first example (log`foo`) allows the language specification to determine the values passed to the log function (See 12.3.7). The second example (log(`foo`)) explicitly passes a single argument.

模板文字可以包含字符串,以及表达。有时您可能希望从字符串部分和表达式部分更多地控制字符串的编译。在这种情况下,您可能正在寻找标记模板。

Template literals can contain strings, as well as expressions. Sometimes you may wish to have more control over the compilation of a string from its string-parts, and expression-parts. In this case, you may be looking for tagged templates.

var name = "Jonathan";
var mssg = foo `Hello, ${name}. Nice name, ${name}.`;

function foo ( strings, ...values ) {
    console.log( strings ); //["Hello, ", ". Nice name, ", ".", raw: Array[3]]
    console.log( values  ); //["Jonathan", "Jonathan"]
}

请注意这里所有的字符串通过第一个参数传入。同样,所有内插值表达式都通过其余参数传递(这里一起拉到一个数组中)。

Notice here how all of the strings are passed in through the first argument. As well, all of the interpolated value expressions are passed in through the rest of the parameters (pulled together into an array here).

通过这个添加的控件,我们可以做各种各样的事情,比如本地化。在此示例中,语言规范确定要传递给函数的适当值—开发人员不会确定这一点。

With this added control, we could do all sorts of things, such as localization. In this example, the language specification determines the appropriate values to pass to the function — the developer doesn't determine this.

相比之下,当你打电话给 log( foo ,最终只得到 结果字符串。没有对象,没有零件,没有原始值。

To contrast, when you call log(foo), you wind up getting only the resulting string. No objects, no parts, no raw values.

这篇关于为什么在使用模板字符串时可以在没有括号的情况下调用函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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