What is the difference between this constructor-based syntax for creating an object:
person = new Object()
...and this literal syntax:
Everyone here is talking about the similarities of the two. I am gonna point out the differences.
Using new Object()
allows you to pass another object. The obvious outcome is that the newly created object will be set to the same reference. Here is a sample code:
var obj1 = new Object();
obj1.a = 1;
var obj2 = new Object(obj1);
obj2.a // 1
The usage is not limited to objects as in OOP objects. Other types could be passed to it too. The function will set the type accordingly. For example if we pass integer 1 to it, an object of type number will be created for us.
var obj = new Object(1);
typeof obj // "number"
The object created using the above method (new Object(1)
) would be converted to object type if a property is added to it.
var obj = new Object(1);
typeof obj // "number"
obj.a = 2;
typeof obj // "object"
If the object is a copy of a child class of object, we could add the property without the type conversion.
var obj = new Object("foo");
typeof obj // "object"
obj === "foo" // true
obj.a = 1;
obj === "foo" // true
obj.a // 1
var str = "foo";
str.a = 1;
str.a // undefined