简体   繁体   English

ES6模板字符串和自动分号插入

[英]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 失败并出现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. 由于您的表达式`abc`.split(`b`) `abc`.split(`b`)在语法上是有效的,因此此处不会发生自动分号插入 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. 并不是说ASI在做一些怪异的事情,它只是在您期望的时候什么也没做。

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 ` . 如果你想省略分号,让他们自动插入需要的地方有可能 ,您将需要把一个在开始每一个开头线([/+-`

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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