javascript

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!'; 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.

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

Related Question Allowed/recommended property names in object literals in javascript Object Literals vs. Functions Understanding JavaScript anonymous vs. named functions in object literals Can you create object property names using template literals in javascript? Property names with spaces in object literals Object in Template Literals vs. Outside Javascript Object Literals for property with method Dependency property in wpf/silverlight vs. javascript object property Is it possible to control how object property names get converted to strings in JavaScript? Object vs. var [JavaScript]
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM