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

Why Does This Work?

var Me = {
                "name": "Andy";
        greet: function () {
            console.log("Hello, I'm " + this.name);
        }
};

var Richard = {
            "name": "Richard",
            greet: Me.greet //works because we're not dealing with things that are inside a function?
};

Me.greet();
Richard.greet();

Returns: "Hello, I'm Andy" and "Hello, I'm Richard"

I'm not sure how Me.greet is accessible from inside the Richard object? Is it simply because we're not dealing with things inside functions, therefore it's all in the same Scope?

1 Answer

Kevin Kenger
Kevin Kenger
32,834 Points

Hey Andrew,

You're right. Both objects are in the same scope. Scope is defined only by functions, so your Me object is a global object, given that it isn't inside of a function. This means that any properties that belong to it, like greet in this case, are accessible from anywhere.

I have to say thought, Kevin, the last module, 'Prototypes 2', bent my mind. Completely lost me!