简体   繁体   English

何时使用Javascript对象文字

[英]When to use Javascript object literals

When should object literals be used in javascript, sometimes I get confused I am trying to apply oop concepts and pattern to the language. 什么时候应该在javascript中使用对象文字,有时我会感到困惑我试图将oop概念和模式应用于语言。 I am trying to not just use procedural programming concepts because I know the language has amazing capabilities. 我试图不仅仅使用过程编程概念,因为我知道该语言具有惊人的功能。

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. 第二个在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. 你的帖子的潜台词暗示你试图将一些非Javascript概念印在Javascript上。 I see this a lot (particularly where people try and make everything OO in PHP as the most egregious example). 我看到了很多(特别是在人们尝试将PHP中的所有OO作为最令人震惊的例子的地方)。 Javascript has its own strengths and weaknesses. Javascript有自己的优点和缺点。 Play to those. 玩那些。 Don't try to make it something it isn't. 不要试图让它成为现实。

One common mistake is that people confuse OO with Classical language design. 一个常见的错误是人们将OO与古典语言设计混为一谈。 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. 你真的不想在类的方面考虑javascript,你想要在功能,鸭子打字和原型方面进行思考。

This may seem obvious but Javascript object literals are also commonly used for data exchange with other systems. 这似乎很明显,但Javascript对象文字也常用于与其他系统进行数据交换。 JSON after all is just a subset of Javascript object literal syntax. 毕竟JSON只是Javascript对象文字语法的一个子集。

Object literals also play an important role in JSON . 对象文字在JSON中也起着重要作用。 Though it is important to note JSON is language independent. 虽然重要的是要注意JSON与语言无关。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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