问题
Is there a reason (performance or other) not to use backtick template literal syntax for all strings in a javascript source file? If so, what?
Should I prefer this:
var str1 = \'this is a string\';
over this?
var str2 = `this is another string`;
回答1:
The most significant reason not to use them is that ES6 is not supported in all environments.
Of course that might not affect you at all, but still: YAGNI. Don't use template literals unless you need interpolation, multiline literals, or unescaped quotes and apostrophes. Much of the arguments from When to use double or single quotes in JavaScript? carry over as well. As always, keep your code base consistent and use only one string literal style where you don't need a special one.
回答2:
Code-wise, there is no specific disadvantage. JS engines are smart enough to not have performance differences between a string literal and a template literal without variables.
In fact, I might even argue that it is good to always use template literals:
You can already use single quotes or double quotes to make strings. Choosing which one is largely arbitrary, and you just stick with one. However, it is encouraged to use the other quote if your string contains your chosen string marker, i.e. if you chose
'
, you would still do"don't argue"
instead of'don\'t argue'
. However, backticks are very rare in normal language and strings, so you would actually more rarely have to either use another string literal syntax or use escape codes, which is good.For example, you'd be forced to use escape sequences to have the string
she said: "Don't do this!"
with either double or single quotes, but you wouldn't have to when using backticks.- You don't have to convert if you want to use a variable in the string in the future.
However, those are very weak advantages. But still more than none, so I would mainly use template literals.
A real but in my opinion ignorable objection is the one of having to support environments where string literals are not supported. If you have those, you would know and wouldn't be asking this question.
回答3:
Always use string literals. In this case YAGNI is not correct. You absolutely will need it. As some point, you will have add a variable to your string, at which point you will either need to change single quotes to backtickets, or use the dreaded '+'.
来源:https://stackoverflow.com/questions/37777677/is-there-a-downside-to-using-es6-template-literals-syntax-without-a-templated-ex