Initializing a Javascript object, which is the best way to do this?

Object initialization:

var myObject = {}; 

and

 var myObject = new Object(); 

why is the latter considered antipattern?

thanks

+4
source share
4 answers

I'm not sure that new Object() really falls under the "anti-pattern", but usually {} it is shorter and more flexible at the same time.

When you write JavaScript, you want it to end short ... if it can be concise and clear when writing, as this:

 var myObject = { key: "value" }; 

... then you get the best of both worlds. Also, when you create objects inside objects, for example:

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

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

+7
source

You should always prefer literals over constructors.

This is not related to your question, but here is an example with arrays. new Array() can be confusing at a glance if you don't know how this works:

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

both create arrays of length 2 and 1, respectively. But consider

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

The former creates an array of length 2 containing elements 5 and 6, the latter creates an array of empty length 5.

So you see, using literal notation, avoids this trap.

In addition, a literal designation is always used. When you create a string, you also write var t = "Hello world" , not var t = new String("Hello world") .

+4
source

Good anti-pattern due to a problem with array constructors, it just agrees to use literals {} instead of constructors in Object new Object , See the Google Javascript Guides. .

+1
source

Almost always yes

I think that things like “you should always prefer this” are too generalized, there are always exceptions. Object literals are almost always preferable, but what to do when you try to clone complex sets of objects? Or trying to create a module ?

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

Source: https://habr.com/ru/post/1333333/


All Articles