
上QQ阅读APP看书,第一时间看更新
Template literals
Template literals provide the ability to embed expressions in string literals and support multiple lines. The syntax is to use the back-tick (`) character to enclose the string instead of single quotes or double quotes. Here is an example:
let user = {
name: 'Ted',
greeting () {
console.log(`Hello, I'm ${this.name}.`);
}
};
user.greeting(); // Hello, I'm Ted.
As you can see, inside the template literals, you can access the execution context via this by using the syntax ${...}. Here is another example with multiple lines:
let greeting = `Hello, I'm ${user.name}.
Welcome to the team!`;
console.log(greeting); // Hello, I'm Ted.
// Welcome to the team!
One caveat is that all the whitespaces inside the back-tick characters are part of the output. So, if you indent the second line as follows, the output wouldn't look good:
let greeting = `Hello, I'm ${user.name}.
Welcome to the team!`;
console.log(greeting); // Hello, I'm Ted.
// Welcome to the team!