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

后端 未结 3 498
北荒
北荒 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 02:48

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

    No (starting with ES5).

    The definition of property in the spec is that it is any identifier name. class is a perfectly good identifier name.

    As others have pointed out in the comments, according to the spec, the property name in an object literal may be an (unquoted) IdentifierName (in addition to being a string etc.). IdentifierName is, for all practical purposes, any sequence of Unicode "letters", as given in section 7.6.

    Note that the syntax error generated by

    const {class} = obj;
    

    is not an exception. That's not an object literal, which is what the question is about; it's an assignment (or the destructuring kind), which attempts to assign a variable class. Of course you can't, never have been able to, and never will be able to have variables which are named with reserved words.

    See also this blog post, which although not authoritative is a reliable, high-quality source of information about all things ES5/6/7.

    Note that in ES3, the definition of PropertyName was Identifier, not IdentifierName as in ES5. That prevented using properties such as class, since class is not an identifier. It was this change that permitted the use of unquoted reserved words as properties in object literals (as well as in dot notation).

    With regard to "jQuery objects", a "jQuery object" is just a regular old JS object. Do you mean the DOM elements held by jQuery objects? They are a kind of hybrid of native objects and JS objects. As JS objects, they can have properties. However, they cannot be written in object literal form, so the question does not really apply to them. (As native (DOM) objects, they can have attributes, the latter case not being covered by the JS spec.)

提交回复
热议问题