gpt4 book ai didi

javascript - javascript对象的属性名设置保留字需要加引号吗?

转载 作者:可可西里 更新时间:2023-11-01 01:22:49 25 4
gpt4 key购买 nike

给定一个对象字面量或 jQuery(html, attributes) 对象,是否有任何规范规定必须引用保留字或将来的保留字?

或者,例如,可以将 class 设置为对象的属性名称,而无需使用引号将属性名称括起来,这种做法不违反有关标识符、属性名称的规范,还是使用保留字?

寻求关于此问题的结论性答案以避免混淆。

let objLit = {
class: 123,
var: "abc",
let: 456,
const: "def",
import: 789
}

console.dir(objLit);

jQuery("<div>012</div>", {
class: "ghi"
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>

相关:

规范

Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications.
An Identifier is an IdentifierName that is not a ReservedWord

最佳答案

ECMAScript 5+

不,自 ECMAScript 5 以来不需要引号。原因如下:

正如您在帖子中提到的,来自 ECMAScript® 5.1 Language Specification :

7.6 Identifier Names and Identifiers

Identifier Names are tokens that are interpreted according to the grammar given in the “Identifiers” section of chapter 5 of the Unicode standard, with some small modifications. An Identifier is an IdentifierName that is not a ReservedWord (see 7.6.1).

[...]

Syntax

Identifier ::
IdentifierName but not ReservedWord

根据规范,ReservedWord 是:

7.6.1 Reserved Words

A reserved word is an IdentifierName that cannot be used as an Identifier.

Syntax

ReservedWord :: 
Keyword
FutureReservedWord
NullLiteral
BooleanLiteral

这包括关键字、 future 关键字、null 和 bool 文字。完整名单如下:

7.6.1.1 Keywords

break    do       instanceof typeof
case else new var
catch finally return void
continue for switch while
debugger function this with
default if throw
delete in try

7.6.1.2 Future Reserved Words

class enum   extends super
const export import

7.8.1 Null Literals

null

7.8.2 Boolean Literals

true
false

以上(第 7.6 节)暗示 IdentifierName 可以是 ReservedWord,并且来自 object initializers 的规范:

11.1.5 Object Initialiser

[...]

Syntax

ObjectLiteral :
{ }
{ PropertyNameAndValueList }
{ PropertyNameAndValueList , }

根据规范,PropertyName 是:

PropertyName :
IdentifierName
StringLiteral
NumericLiteral

如您所见,PropertyName 可能是 IdentifierName,因此 ReservedWord 可以是 PropertyName秒。这最终告诉我们,根据规范,允许使用 ReservedWord,例如 classvar 作为PropertyName 不带引号,就像字符串文字或数字文字一样。


ECMAScript <5

要更深入地了解为什么在 ES5 之前的早期版本中不允许这样做,您必须查看 PropertyName 是如何定义的。根据 ECMAScript® 3 Language Specification :

PropertyName :
Identifier
StringLiteral
NumericLiteral

如您所见,PropertyName 是一个 Identifer - 而不是 IdentifierName,因此导致无法使用 ReservedWords 作为 PropertyNames。

关于javascript - javascript对象的属性名设置保留字需要加引号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40209367/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com