开发者

JavaScript Object Literals: Property names as strings vs. "raw"

Can there ever be a difference between:

var x = {
  hello: 'world'
};

and

var x = {
  'hello': 'world'
};

?

That is, under what conditions does giving a property name as a string have different results than giving it as a "raw" name? For example, I know that var x = {}; x['@£$%'] = 'bling!'; is valid (since any string can be a property), but x.@£$% = 'bling!' won't work. Neither will language keywords or reserved keywords as property names (so var x = {for: 'good', class: 'y'}; won't work.

开发者_如何学C

Anything else?

For example, what if

var hello = 'goodbye'; 

is defined in the above example? Or something else, like

function hello() { 
  return 'goodbye';
}

?

Should I always make my property names strings, just to be safe?


I almost never specify anything beyond a-zA-Z as my key so I don't really worry about characters such as @. If for whatever reason you really need these characters, then sure go ahead and use quotes.

If you are sure the key word is a reserved word or even remotely think it may be, just wrap it in quotes and be safe .. otherwise just go quoteless and save typing time.

A variable with the same name as your key has absolutely no bearing because it's taken literally.

var hello = 'god';
({hello:2})['hello'] // 2


In an object literal, you can use either a string literal (quoted) or an identifier (unquoted). In the first case, you can therefore use whatever characters you like, while in the second, you have to follow the rules for identifiers laid out in the ECMAScript spec. The same identifier rules apply when using the dot notation property accessor. Simplified summary:

  • The identifier must start with a letter, _ or $ (both of which may also appear anywhere in the identifier)
  • After the first character, more characters are allowed, including numbers
  • The identifier must not be a reserved word (new, var, function, delete, etc)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜