Why can functions be called without parentheses when using template strings? [duplicate]

坚强是说给别人听的谎言 提交于 2019-11-30 04:42:22
Sampson

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.

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!