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 Object-Oriented JavaScript (2015) Constructor Functions and Prototypes Creating Multiple Instances with Constructors

Constructor variables

For JS constructor variables. We use something like "this.name = name".

However, we don't have variables named "name". Shouldn't we have to create it first?

1 Answer

Hey Tony, So a constructor function might look like this right?

function myThingy(name, color, type) {
    this.name = name; //line 1
    this.color = color; //line 2
    this.type = type; // line 3
}

Well, this.name would then refer to the current instance of this constructor function.... ya know, whatever new myThingy() might be. When it says = name, it's not creating a new variable though. It's actually just referencing the value of the parameter "name".

In other words, line 1 says that every time you create a new object using this constructor, the first argument supplied to that new object, becomes equal to (becomes the value of) that new object's "name" property. And line 2 says the same thing... except every new object gets a "color" property equal to the 2nd argument supplied. And same with the line 3, with the 3rd argument supplied.

Hope that makes sense. No variables are being declared here.

Got it. So it's making the property and not a variable. I'm having a hard time because I'm thinking of constructors in Java and you have to make the variables.

Mmm I feel you. It's weird coming from a classical inheritance language and dealing with JavaScript's prototypal inheritance. You should check this article out here. It does a great job of helping you connect the dots. Kinda of a long read though, but its worth it man.