js模板字符串自定义类名,模板字符串作为对象属性名称

Why does JavaScript not allow a template string as an object property key? For example, when I input:

foo = {`bar`: 'baz'}

into the NodeJS REPL, it throws a SyntaxError with "Unexpected template string" with a long stack trace. Property values are fine, however, which is not as unexpected. Similar errors happen in the browser, for example, Firebug throws a SyntaxError with "invalid property id".

Template strings are allowed in "computed property names". For instance, this compiles perfectly fine in all browsers that support the syntax:

var foo = {

[`bar` + 1]: `baz`

};

and creates the object {"bar1": "baz"}.

Why are template strings not allowed as literal object keys? Is it for performance reasons? Template strings must be compiled, possibly at runtime (correct me if I'm wrong), which means every time it encounters this object, the interpreter will have to compute the object name. Factoring in things like "cooked" template strings, this seems like it could get slow, although we have had getters and setters since ES5. Firefox does not mention this as an error, which is why I found it unexpected. Will the syntax be allowed sometime in the future?

解决方案Why are template strings not allowed as literal object keys?

Template strings are expressions, not literals1. You can only use string literals (and identifiers) for property names, for everything else - that is not known to be static - you need a computed property name.

Is it for performance reasons?

No, that's unlikely. It's to ease parsing, and makes it easy to distinguish constant (statically known) property names from dynamically computed ones.

And mostly, it's a feature that no one needs. It doesn't simplify or shorten anything, and what you would achieve with it is already possible.

Will the syntax be allowed sometime in the future?

Nope.

1: Even when they're called "template literals", technically they aren't literals. And: templates don't even need to be strings, they can evaluate to anything.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值