简体   繁体   中英

ES6 template strings and the automatic semicolon insertion

Consider the following code:

`abc`.split(`b`)
`abc`.split(`b`)

This fails with TypeError: "abc".split(...) is not a function

Try it here.

To make it work, we need to insert a semicolon between those two statements. Also the code works fine if we use a regular string on the second line:

`abc`.split(`b`)
"abc".split(`b`)

What is the reason for this behaviour?

I guess it has something to do with the automatic semicolon insertion doing some whacky stuff, but I can't figure out what this would be.
Also the fact that there seems to be a difference between regular and template strings kinda confuses me. Shouldn't those be equivalent?

Template literals can be tagged with a function , string literals cannot. Notice that

tag`a ${x} b`;

is basically equivalent to

tag("a ", x, " b");

Since your expression `abc`.split(`b`) `abc`.split(`b`) is grammatically valid, there is no automatic semicolon insertion happening here. Don't omit the semicolons where they are necessary. It's not that ASI is doing whacky stuff, it's just doing nothing while you expect it to.

If you want to omit semicolons and let them be automatically inserted where ever possible needed, you will need to put one at the begin of every line that starts with ( , [ , / , + , - or ` .

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