Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

John McErlain
John McErlain
12,508 Points

Doesn't the Javascript keyword "new" create a new object?

While taking Andrew's API course, the teacher's notes referenced the book "Javascript Patterns", in which (p.142) I noticed this snippet:

var uni = new Universe();
var uni2 = new Universe();
uni === uni2; // true

My question is this: In what universe does uni === uni2 ?

To test the author's code, I wrote the constructor as follows:

function Universe(){
  this.start_time = 0;
  this.bang = "BIG";
}

Then tested with the following:

var uni = new Universe();
var uni2 = new Universe();
console.log(uni === uni2); // the author states this is "true" but my node clearly returns "false"!

Can anybody clarify this for me?

1 Answer

Thomas Nilsen
Thomas Nilsen
14,957 Points

When you create the following function:

function Universe() { 
    this.start_time = 0; 
    this.bang = "BIG"; 
}

A property object called prototype is being created internally.

If you create a new instance using new Universe(), that instance will have a proto property pointing to the Universe.prototype.

So the following will be true:

var uni1 = new Universe();
var uni2 = new Universe();

console.log(uni1.__proto__ === Universe.prototype);     //true
console.log(uni1.__proto__ === uni2.__proto__);         //true
John McErlain
John McErlain
12,508 Points

Hi Thomas, after reading your answer and pondering the equality of an object's proto property to the constructor's prototype, I still could not understand how (uni === uni2) might return 'true'.

After re-reading the author's chapter (which was on creating a singleton), I came to realize that his assertion (uni === uni2) is 'true' only AFTER the singleton is created.

The author states "In this example, uni is created only the first time the constructor is called. The second time (and the third, fourth, and so on) the same uni object is returned. This is why uni === uni2—because they are essentially two references pointing to the exact same object."

But that is true ONLY AFTER the singleton is created. He made the assertion before he showed the methodology and that is what threw me. Apparently, he was stating 'expected behavior'.

Thank-you for your answer.