Javascript 对象初始化,这是最好的方法吗?
对象初始化:
var myObject = {};
为什么
var myObject = new Object();
最后一个被认为是反模式?
谢谢
Object initialization:
var myObject = {};
and
var myObject = new Object();
why the last one is considered an antipattern?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不确定
new Object()
是否真的属于“反模式”,但{}
通常是首选,它简洁,同时更灵活。当你编写 JavaScript 时,你希望它能够简短……如果在编写 JavaScript 时也能简洁易懂,就像这样:
……那么你就可以两全其美。此外,当您在对象中创建对象时,例如:
...那么您会发现它比替代的
new Object()
语法更具可读性。I'm not sure
new Object()
really falls under "anti-pattern", but{}
is usually preferred, it's terse and more flexible at the same time.When you're writing JavaScript you want it to end up short...if it can be terse and understandable when writing it as well, as this is:
...then you get the best of both worlds. Also when you're creating objects within objects, for example:
...then you can see it's much more readable than the alternative
new Object()
syntax.你总是应该更喜欢文字而不是构造函数。
这与您的问题并不真正相关,但这是一个数组的示例。如果您不知道 new Array() 是如何工作的,乍一看可能会感到困惑:
两者都创建长度分别为 2 和 1 的数组。但考虑
第一个创建一个长度为 2 的数组,包含元素 5 和 6,
最后一个创建了一个长度为5的空数组。
所以你看,使用文字表示法可以避免这个陷阱。
除此之外,始终使用文字表示法是一致的。创建字符串时,您还可以编写
var t = "Hello world"
而不是var t = new String("Hello world")
。You always should prefer literals over constructors.
This is not really related to your question but here is an example with arrays.
new Array()
can be confusing at the first glance if you don't know how it works:both create arrays with length 2 and 1 resp. But consider
The first one creates an array of length 2 ,containing the elements 5 and 6,
the last one creates an empty array of length 5.
So you see, using literal notation avoids this pitfall.
Besides that, always using literal notation is consistent. When you create a string you also write
var t = "Hello world"
and notvar t = new String("Hello world")
.好吧,由于数组构造函数的问题,反模式仍然使用文字
{}
,而不是对象中的构造函数new Object
,查看 Google Javascript 指南。Well anti-pattern because of a problem with array constructors, it's just convention to still use literals
{}
, instead of constructors in Objectsnew Object
, See Google Javascript Guides.几乎总是,是的,
我认为说“一个人应该总是更喜欢这个”之类的话有点太笼统了,总有例外。对象字面量几乎总是首选,但是当您尝试克隆复杂的对象集时该怎么办?或者尝试实例化 模块 ?
Almost Always, yes
I think saying things like "one should always prefer this" is a bit too generalized, there are always exceptions. Object literals are almost always preferred, but what to do when you are trying to clone complex sets of objects?? Or trying to instantiate module?