4

When I do:

var person = new Object();  
person.name = "alex";
console.log(person)

output is:

Object { name="alex"}

However, say I drop the "new" word and do:

var person = Object();  
person.name = "alex";
console.log(person)

Output is also:

Object { name="alex"}

Why?

dublintech
  • 16,815
  • 29
  • 84
  • 115

2 Answers2

4

Because some built-in functions are just defined to act this way. For example see ES5 15.2.1.1 for Object:

15.2.1.1 Object ( [ value ] )

When the Object function is called with no arguments or with one argument value, the following steps are taken:

  1. If value is null, undefined or not supplied, create and return a new Object object exactly as if the standard built-in Object constructor had been called with the same arguments (15.2.2.1).
  2. Return ToObject(value).

They test whether they have been called with new or not and if not act like they'd have been called with new.

Not all constructors work like this. For example Date will return a string when called without new.


You can implement this yourself:

function Foo() {
    if(!(this instanceof Foo)) {
        return new Foo();
    }
    // do other init stuff
}

Foo() and new Foo() will act the same way (it gets more tricky with variable arguments though).

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
0

Since your example is an Object type of built-in function, as it is answered above it is the same for this type, it does not work the same way for most of the other built-in functions such as Number(). You should be very careful when invoking them with the 'new' keyword or not. Because by default the 'new' keyword with a function constructor returns an object, not a primitive type directly. So you can not, for example, check strict equality on two variables that one of them is declared and assigned using new Number() , and the other is with Number()

An example would be:

var num1 = Number(26); 
var num2 = new Number(26);

num1 == num2; // returns true

num1 === num2; // returns false

You may checkout the difference at the console log:

console.log(num1);
> 26

console.log(num2);
> Number {26}
>     __proto__: Number
>     [[PrimitiveValue]]: 26