Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between new Object and new Object() in JavaScript [duplicate]

Tags:

javascript

Possible Duplicate:
new MyObject(); vs new MyObject;

In some articles I seen following statement to create new object in JavaScript:

var myObject = new Object;

and at some sites:

var myObject = new Object();

In there is any difference between two statements or one is just shorthand?

like image 441
daljit Avatar asked Feb 20 '12 11:02

daljit


People also ask

What is difference between and new object in JavaScript?

There are no differences.

What is the difference between object create and new object?

The major difference is that Object. Create returns the new object while the constructor function return the constructor of the object or the object. This is due to the important difference that new actually runs constructor code, whereas Object. create will not execute the constructor code.

What is new object in JavaScript?

The new keyword is used in javascript to create a object from a constructor function. The new keyword has to be placed before the constructor function call and will do the following things: Creates a new object. Sets the prototype of this object to the constructor function's prototype property.

What is the difference between an object and an object literal?

Objects created using object literal are singletons, this means when a change is made to the object, it affects the object entire the script. Whereas if an object is created using constructor function and a change is made to it, that change won't affect the object throughout the script.


3 Answers

There's no difference. Parentheses are optional when using a function as a constructor (i.e. with the new operator) and no parameters. When not using the new operator, parentheses are always required when calling a function.

As noted in another answer, it's generally preferable to use an object literal instead. It has the following advantages over using the Object constructor:

  • Allows concise initialization of properties (e.g. var foo = { bar: "cheese" };)
  • Shorter
  • Possibly faster
  • Unaffected in the (unlikely) event of the Object function being overwritten.
like image 177
Tim Down Avatar answered Oct 19 '22 08:10

Tim Down


Easy answer - don't use that syntax. The preferred way for creating objects in JavaScript is to use the following syntax:

var myObject = {}; // creates an empty object
like image 30
robyaw Avatar answered Oct 19 '22 07:10

robyaw


There is no difference. It just happens that in this special case, you can omit the ().

So new Object()

and

new Object

are equivalent.

BTW, there is also no difference in using new Object() over {}. Use whatever you prefer.

like image 1
helpermethod Avatar answered Oct 19 '22 08:10

helpermethod