Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript

Jonathan Grieve
MOD
Jonathan Grieve
Treehouse Moderator 90,705 Points

Understanding 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
Chris Shaw
26,650 Points

Hi 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
Jonathan Grieve
Treehouse Moderator 90,705 Points

Hmm, 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
Jonathan Grieve
Treehouse Moderator 90,705 Points

Aha! The penny has dropped :)

I still get an undefined after the correct message has been displayed but I'll look into that myself. Thanks. :)