using reserved words as property names, revisited

北战南征 提交于 2019-11-27 07:33:06

In ECMAScript, starting from ES5, reserved words may be used as object property names "in the buff". This means that they don't need to be "clothed" in quotes when defining object literals, and they can be dereferenced (for accessing, assigning, and deleting) on objects without having to use square bracket indexing notation.

That said, reserved words may still NOT be used as identifier names. This is stated quite unambiguously in the spec and is stated somewhat emphatically here (if you don't want your eyes to bleed by having to read the actual language spec)...

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Reserved_Words

The following are keywords and may not be used as variables, functions, methods, or object identifiers, because ECMAScript specifies special behavior for them:

RoToRa

I'm not quite sure what the point is you want to make, so the only answer I can give is: Yes, it's ok to use reserved words as property names.

(However two small remarks: foo["class"] is ok, not foo[class]. And any way you should be using form.elements["xyz"] and not form.xyz to access an element named xyz.)

Yes, it can be used.

Just small remark, if you use YUI compressor you have to put property name which is equal to one of js reserved words in quotes.

For example, this won't compress

var a = { case : "foo"}; // syntax error, "invalid property id"
a.for = "bar"; // syntax error, "missing name after . operator"

This will do

var a = { "case" : "foo"}; //OK
a["for"] = "bar"; //OK

Here is Online JavaScript/CSS Compression Using YUI Compressor where this can be tested.

Yes, in most browsers (including IE9+)

There's actually an entry in the Kangax compatibility table for "Reserved words as property names"

http://kangax.github.io/compat-table/es5/#test-Object/array_literal_extensions_Reserved_words_as_property_names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!