Do reserved words need to be quoted when set as property names of JavaScript objects?

后端 未结 3 487
北荒
北荒 2020-12-10 02:25

Given an object literal, or jQuery(html, attributes) object, does any specification state that reserved words, or future reserved words MUST be quoted?

Or, can, for

3条回答
  •  执念已碎
    2020-12-10 03:00

    ECMAScript 5+

    No, quotes were not needed since ECMAScript 5. Here's why:

    As mentioned in your post, from the 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
    

    By specification, a ReservedWord is:

    7.6.1 Reserved Words

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

    Syntax

    ReservedWord :: 
      Keyword
      FutureReservedWord
      NullLiteral
      BooleanLiteral
    

    This includes keywords, future keywords, null, and boolean literals. The full list is as follows:

    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
    

    The above (Section 7.6) implies that IdentifierNames can be ReservedWords, and from the specification for object initializers:

    11.1.5 Object Initialiser

    [...]

    Syntax

    ObjectLiteral :
      { }
      { PropertyNameAndValueList }
      { PropertyNameAndValueList , }
    

    Where PropertyName is, by specification:

    PropertyName :
      IdentifierName
      StringLiteral
      NumericLiteral
    

    As you can see, a PropertyName may be an IdentifierName, thus allowing ReservedWords to be PropertyNames. That conclusively tells us that, by specification, it is allowed to have ReservedWords such as class and var as PropertyNames unquoted just like string literals or numeric literals.


    ECMAScript <5

    To go more in depth as to why this wasn't allowed in previous versions before ES5, you have to look at how PropertyName was defined. Per the ECMAScript® 3 Language Specification:

    PropertyName :
      Identifier
      StringLiteral
      NumericLiteral
    

    As you can see, PropertyName was an Identifer - not an IdentifierName, thus leading to the inability for ReservedWords as PropertyNames.

提交回复
热议问题