简体   繁体   中英

'this' inside a template literal

According to the ES6 spec, the syntax

foo`Hello!`

should behave exactly like

foo('Hello!')

Putting a template literal after an expression triggers a function call, similar to how a parameter list (comma-separated values in parentheses) triggers a function call. The previous code is equivalent to the following function call (in reality, the function gets more information, but that is explained later).

Source

However, in the following snippet, binding a value to a function causes the 2 syntaxes to behave differently:

 function alertParans() { alert(this) } function alertNoParans() { alert `${this}` } var executeParans = alertParans.bind('roman empire'); var executeNoParans = alertNoParans.bind('greek empire'); executeParans(); executeNoParans(); 

The first call prints 'roman empire' whilst the second will always just print a comma. Why?

Fiddle

You should read the example you linked to, as it says something different than you claim.

In the section it is stated that the following examples are equivalent :

tagFunction`Hello ${firstName} ${lastName}!`
tagFunction(['Hello ', ' ', '!'], firstName, lastName)

Now if you were to apply this to alert, it would look like this:

function alertParans() { alert(['', ''], this);  }
function alertNoParans() { alert`${this}`;  }

var executeParans = alertParans.bind('roman empire');
var executeNoParans = alertNoParans.bind('greek empire');

executeParans();
executeNoParans();

Now you get the comma in both cases, as the first argument of alert is now always an array with two empty strings. Why?

Because template literals are split into the contents before ( '' ), during ( this ) and after ( '' ) the interpolation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM