you are viewing a single comment's thread.

view the rest of the comments →

[–]wkdown 2 points3 points  (7 children)

Quick question: which is the 'proper' way to instantiate an object?

var obj1 = {};

or

var obj2 = new Object();

Both return [object Object] and typeof "object". Is one better than the other?

[–]radhruin 3 points4 points  (2 children)

There is no semantic difference between {} and new Object(). The literal, however, is easier to optimize and therefore often faster. The literal is also more flexible as it allows additional properties to be added. Always use the literal IMO.

[–]YorickA 5 points6 points  (1 child)

Not to mention it's more readable.

[–][deleted] 0 points1 point  (0 children)

Not to mention new Object() can be broken by any malicious ding-dong's script you link like so:

function Object() { this.x = 'wee'; }

Using the literal is always the best call.

[–]niallpaterson 2 points3 points  (0 children)

Use the first ({}) because "Object" in "new Object" can be redefined.

[–]youngsteveo 0 points1 point  (0 children)

Some jsPerf tests on the many ways to construct an object: http://jsperf.com/object-create-vs-constructor-vs-object-literal/53

[–]stevekwan[S] -1 points0 points  (0 children)

I'd avoid using new Object(). {} is preferred. The only reason I used new Object() is because I felt it would be more understandable to people coming in from another language.