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!
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

Jonathan Grieve
Treehouse Moderator 91,247 PointsUnderstanding Prototypes in Javascript Objects
So i've just finished and studied the Javascript Foundations videos to death on my way through the Front End Track. So i'm quite familiar with this code, from the prototypes section of the course.
var personPrototype = {
name: "anonymous",
greet: function (name, mood) {
name = name || "You";
mood = mood || "good";
console.log("Hello, " + name +
" I am " + this.name +
" and I am in a + mood " + mood + " mood!");
},
species: "Homo Sapien"
}
function Person (name) {
this.name = name;
return this;
}
jim = new Person("Jim", "Bad");
Person.prototype = personPrototype;
Except, I have still not the slightest clue how to get the message, "Hello [N] I am [N] and I am in a + [N] mood!" printed to either the screen or the console, despite whatever combination I put in the console.
So how's it done? I'm all out of ideas.
1 Answer

Chris Shaw
26,676 PointsHi Jonathan,
The most immediate issue I see is you're assigning the prototype after you create a new instance of Person
which is wrong as you're overwriting the parameters you're passing to your constructor, the below is the correct structure.
Also you don't need to return this
as anytime the keyword new
is applied you're creating a new instance of that object thus this
is applied automatically.
function Person (name) {
this.name = name;
}
Person.prototype = personPrototype;
// Create a new instance of `Person`
var jim = new Person('Jim');
As for your question you can easily output the console message using the below.
jim.greet('John', 'happy');
Jonathan Grieve
Treehouse Moderator 91,247 PointsJonathan Grieve
Treehouse Moderator 91,247 PointsHmm, the code in the OP is only what I've followed from the videos. Obviously there's more to it than just following on word for word.
But the jim.greet call still isn't working. undefined on the console.
Jonathan Grieve
Treehouse Moderator 91,247 PointsJonathan Grieve
Treehouse Moderator 91,247 PointsAha! The penny has dropped :)
I still get an undefined after the correct message has been displayed but I'll look into that myself. Thanks. :)