oop - Javascript object initialization, which is the best way to do it? - Stack Overflow

Object initialization:var myObject = {};and var myObject = new Object();why the last one is considered

Object initialization:

var myObject = {};

and

var myObject = new Object();

why the last one is considered an antipattern?

thanks

Object initialization:

var myObject = {};

and

var myObject = new Object();

why the last one is considered an antipattern?

thanks

Share Improve this question edited Dec 25, 2010 at 12:08 Oded 500k102 gold badges893 silver badges1k bronze badges asked Dec 25, 2010 at 12:07 cirpocirpo 8921 gold badge9 silver badges11 bronze badges 0
Add a ment  | 

4 Answers 4

Reset to default 7

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:

var myObject = { key: "value" };

...then you get the best of both worlds. Also when you're creating objects within objects, for example:

var myObject = { subObj: { key: "value" } };

...then you can see it's much more readable than the alternative new Object() syntax.

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:

var a = [5,6];
var b = [5];

both create arrays with length 2 and 1 resp. But consider

var a = new Array(5,6);
var b = new Array(5);

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 not var t = new String("Hello world").

Well anti-pattern because of a problem with array constructors, it's just convention to still use literals {}, instead of constructors in Objects new 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 plex sets of objects?? Or trying to instantiate module?

if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {}
        F.prototype = o;
        return new F();
    };
}
newObject = Object.create(oldObject);

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744253208a4565266.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信