开发者

JS Object navigation-- when to use object.sub and object["sub"]?

Looking at this from a point of semantics, there's two ways to navigate objects in JS, you can either use the dot operator or work through them like it's a nested array.

When is 开发者_JAVA技巧it appropriate to use one operator over the other? Why shouldn't I just use the method with square brackets all the time (it seems more powerful)? They both seems easy to read, but the dot operator looks like it's limited in that it cannot be provided with variable names of nested objects, or work through arrays.


The main reasons for using []

  1. You can't access properties with the names of keywords via the dot notation (at least not in < ES5)
  2. You can use it to access properties given by a string

The reasons for using .

  1. Always using [] makes syntax highlighting, code completion etc. pretty much useless
  2. Even with automatic insertion of the closing counter parts [' is a hell lot slower to type (especially on non US Keyboard layouts)

I mean, just imagine writing Chat['users']['getList']()['sort']()['each'].

Rule of thumb: Use . where ever possible, and fall back to [] when there's no other way.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜