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 trialGerry K
5,877 PointsJust want to clarify the use of the Constructor function
So just to clarify the following code:
function Contact(name, email) { this.name = name; this.email = email; }
var contact1 = new Contact('John', 'john@email.com');
This code above creates an object literal which looks like the following:
contact1 = { name: 'John', email: 'john@email.com' }
So if I want to access: console.log(contact1.name)
this would log 'John' to the console.
I hope someone can confirm that my thinking is correct as I'm having some difficulty cementing this idea based on the video alone.
Thank you!
2 Answers
Steven Parker
231,248 PointsIt seems like you have the right idea.
But the terminology is a bit off. The code with the constructor doesn't create an object literal, just an object. But the code on the next line does show an object literal which is equivalent to the object created by the constructor.
ywang04
6,762 PointsObject literals are great when you only need one object. However, maintaining code with several object literals of the same type can get cumbersome. That's why you'd want to use a constructor function. It will handle the initial creation of objects, and will let you create as many objects of the same type as you'd like.