模板字符串作为对象属性名称 [英] Template String As Object Property Name

查看:597
本文介绍了模板字符串作为对象属性名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么JavaScript不允许模板字符串作为对象属性键?例如,当我输入时:

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

foo = {`bar`: 'baz'}

进入NodeJS REPL,它会抛出一个带有Unexpected模板字符串的 SyntaxError 长堆栈跟踪。但是,属性值很好,这并不是意料之外的。在浏览器中发生类似的错误,例如,Firebug使用无效的属性id抛出 SyntaxError

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`
};

并创建对象 {bar1:baz}

为什么不允许模板字符串作为文字对象键?是否出于性能原因?必须在运行时编译模板字符串(如果我错了,请纠正我),这意味着每次遇到此对象时,解释器都必须计算对象名称。考虑到煮熟的模板字符串之类的东西,这似乎可能会变慢,尽管我们从ES5开始就有吸气剂和固定器。 Firefox没有提到这是一个错误,这就是我发现它意外的原因。将来某个时候会允许语法吗?

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?

模板字符串是表达式,而不是文字 1 。您只能对属性名称使用字符串文字(和标识符),对于其他所有内容 - 不知道是静态的 - 您需要计算属性名称。

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?

不。

1:即使他们被称为模板文字,从技术上讲它们不是文字。并且:模板甚至不需要是字符串,它们可以评估任何内容。

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.

这篇关于模板字符串作为对象属性名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆