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

this.prototype - declared within constructor

In the video for JavaScript Foundations > Objects > Prototype 2, a constructor for Person is declared and there is a separate statement setting Person.prototype to personPrototype:

function Person (name) {
    this.name = name;
}

Person.prototype = personPrototype;

Is there any reason you couldn't set Person.prototype like this:

 function Person (name) {
    this.name = name;
    this.prototype = personPrototype;
}

3 Answers

That's a great question, Ezra Seligsohn! The this keyword refers to the current object, not the current class. So, in the context of the constructor, this would refer to the instance being constructed, not the class itself. Using Person.prototype refers to the class rather than the instance, which is what we need to do.

The difference between classes and objects can be a little confusing. Classes are the blueprint for objects - what type of data and methods are supported on it, whereas the object itself is an actual instance of that blueprint.

Good explanation. I understand the difference between classes and objects. But in my example, using "this.prototype" wouldn't that essentially be passing in the prototype to each instance of Person created, essentially the same thing as just passing prototype to the Person class? I realize it would be redundant, uncessarry code, but would it not accomplish the same thing?

It won't work inside the constructor. Here's a Fiddle that shows what happens: Prototype in constructor vs. outside constructor. It basically errors out because hello isn't on the PersonInConstructor instance.

Okay, I see that. Thank you for the awesome example/demonstration!