When to use Javascript object literals

2020-07-09 10:37发布

When should object literals be used in javascript, sometimes I get confused I am trying to apply oop concepts and pattern to the language. I am trying to not just use procedural programming concepts because I know the language has amazing capabilities.

标签: javascript
4条回答
可以哭但决不认输i
2楼-- · 2020-07-09 10:56

Object literals are most commonly used as:

  • a type of associative array; and
  • a way of passing many arguments to a function.

The second is particularly important and common in libraries like jQuery.

That's how they're commonly used. As for when you should use them, that's a difficult question to answer because it's a bit like asking when should arrays be used. Object literals are a tool. They're a means to an end not an end in itself.

The subtext of your post suggests you're trying to imprint some non-Javascript concepts onto Javascript. I see this a lot (particularly where people try and make everything OO in PHP as the most egregious example). Javascript has its own strengths and weaknesses. Play to those. Don't try to make it something it isn't.

查看更多
放荡不羁爱自由
3楼-- · 2020-07-09 10:59

Object literals also play an important role in JSON. Though it is important to note JSON is language independent.

查看更多
家丑人穷心不美
4楼-- · 2020-07-09 11:02

One common mistake is that people confuse OO with Classical language design. You really don't want to be thinking in terms of classes when it comes to javascript, you want to be thinking in terms of functions, duck typing, and prototypes.

查看更多
【Aperson】
5楼-- · 2020-07-09 11:03

This may seem obvious but Javascript object literals are also commonly used for data exchange with other systems. JSON after all is just a subset of Javascript object literal syntax.

查看更多
登录 后发表回答