简体   繁体   中英

javascript: is there any advantage or difference in specifying properties names as text when using literal objects?

all right, it's far easier showing some code...

Is there any performance or any other kind of difference between this javascript code

var obj = {
  'id':   0,
  'name': 'new obj'
};

and

var obj = {
  id:   0,
  name: 'new obj'
};

(Have a look at the single quotes surrounding id and name)

--

If I recall correctly, in php it was adviced to always use the single quotes, because if not the interpreter had to check if there existed a variable with that name...

If your object has names that are not legal identifiers (have spaces or punctuation, start with numbers), or are reserved or keywords, or are the same as any variable in scope, they have to be quoted. Otherwise it doesn't matter, javascript uses the names you give it.

no performance difference i believe.

Usually we use quotes to use reserved words in JavaScript like class , which is not allowed to be used as an object key.

As kennebec points out, some characters are not allowed in unquoted keys.

The main point however (in my opinion) is that the difference is so small that optimalisation on these kind of things is not really worth it. Find other bottlenecks (loops and AJAX calls most often) and fix those first, before going to do micro optimalisation.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM