Vader
Vader

Reputation: 6736

Creating an object using a constructor with and without `new`

I have noticed I can create the same object using a constructor in two different ways.

var myObj = Object()

var myObj = new Object()

I can add properties to both using these methods. myObj.age = 1 and myObj['age'] = 1. The properties of both can be accesed the same way.

So what is the actual difference between these two ways I created myObj? Also is one of these the better way to create an object?

Upvotes: 1

Views: 90

Answers (2)

StriplingWarrior
StriplingWarrior

Reputation: 156728

The difference is that the first one simply calls Object() as a function, within the scope of the window object.

The second one actually instantiates a new object. It's the one you want to use to create an object.

The difference may not be obvious with the Object() function, but let's say you create your own type, like so:

function User(name) {
    this.name = name;
}
var u1 = User("John");
var u2 = new User("Jane");

console.log(u1); // *undefined* because `User()` doesn't return anything.
console.log(this.name); // John
console.log(window.name); // John
console.log(u2.name); // "Jane"

The Object function itself is a special case--it does create a new Object. But since most functions don't work that way, it's good to get in the habit of using the new keyword when instantiating things. If you're just creating a plain old Object, on the other hand, most people prefer the more concise syntax:

var myObj = {};

Upvotes: 4

Koen
Koen

Reputation: 288

The first statement is a function call, meaning that myObj will get whatever is returned in the Object() function. As it happens, the function Object() will provide you with a reference to an Object object, whereas 'normal' constructors will not.

See f.e. the following:

function O(){
  this.bla= "bla";
  return this;
}

Calling O() here will yield a reference to window, not to an instance of O.

Upvotes: 2

Related Questions