给定一个对象字面量或 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 anIdentifierName
that is not aReservedWord
(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 anIdentifier
.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
,例如 class
和 var
作为PropertyName
不带引号,就像字符串文字或数字文字一样。
ECMAScript <5
要更深入地了解为什么在 ES5 之前的早期版本中不允许这样做,您必须查看 PropertyName
是如何定义的。根据 ECMAScript® 3 Language Specification :
PropertyName : Identifier StringLiteral NumericLiteral
如您所见,PropertyName
是一个 Identifer
- 而不是 IdentifierName
,因此导致无法使用 ReservedWord
s 作为 PropertyName
s。
关于javascript - javascript对象的属性名设置保留字需要加引号吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40209367/