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?

2
  • 1
    The Object() constructor behaves identically with and without the new keyword. That's just how it works. Commented Mar 16, 2012 at 23:27
  • Note that Array() and new Array() work the same way too. Commented Mar 16, 2012 at 23:32

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.