What does this `…${…}…` code in the node docs mean? [duplicate]

蹲街弑〆低调 提交于 2019-11-26 10:01:04

问题


This question already has an answer here:

  • Usage of the backtick character (`) in JavaScript? 7 answers

I am to trying to learn Express library and Node.js one step at a time. First I am looking at is the specifics of the Node reqiure(moduleName) function.

I took a look at the documentation for this, and found some weird code in the example documentation:

const circle = require(\'./circle.js\');
console.log( `The area of a circle of radius 4 is ${circle.area(4)}`);

More specifically the ${circle.area(4)} bit.

From what I understand the $ in JavaScript is just like any other variable. When we are using it on client side web development it is used as a delegate for the document function (I think). What is it assigned to when using node?

On top of that, what does this syntax mean? ${circle.area(4)}

If $ is just a reference to some function someFunction(), wouldn\'t it be equivalent to this someFunction(){cirle.area(4)}. I am not seeing how that could be valid syntax.

Also, why wouldn\'t they just directly call the circle.area() function directly anyways?


回答1:


This:

`The area of a circle of radius 4 is ${circle.area(4)}`

is an example of ES2015 template strings.

It interpolates whatever circle.area(4) represents directly into the string. If you're curious about this or other ES2015 features, I recommend checking out Babel and playing around in the REPL.

Here's a very simple example to get you started.

You can see this ES2015 code:

const foo = 'some text';
console.log(`${foo} is interpolated.`);

is transpiled to its ES5 equivalent - a simple + concatenation:

var foo = 'some text';
console.log(foo + ' is interpolated.');


来源:https://stackoverflow.com/questions/36107981/what-does-this-code-in-the-node-docs-mean

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