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

how to access the method that is inside the method of a object.

var app = app || {}; app.common = { setImageAttributes: function() { //alert('set attributes now working');

var imgAttr= { height:50, source:"x", populateAttr: function () { //return this.height+ " " + this.source; alert('this is working');

}

}

}, bindUIelements() { // alert('now working'); this.setImageAttributes(); },

init: function() { this.bindUIelements(); },

};

app.common.setImageAttributes();

"how to get the populateAttr return"

1 Answer

I've cleaned up your code a bit:

let app = {};
app.common = {
    setImageAttributes: function()    {
        // alert('set attributes now working');

        const imgAttr =
            {
                height:50,
                source:"x",
                populateAttr: function () {
                    return this.height+ " " + this.source;
                    // alert('this is working');
                }
            }

    }, bindUIelements() {
        // alert('now working');
        this.setImageAttributes();
    },

    init: function() {
        this.bindUIelements();
    }

};

app.common.setImageAttributes();

The problem you're running into, is that you're trying to access a function within a variable that hasn't been set when you call the outer function. Once you call setImageAttributes, it will create the variable imgAttr, which is only accessible within the scope, since this is where it's declared. If you want to call this function, you must call it within the scope, after the variable is declared, so something like this:

let app = {};
    setImageAttributes: function()    {
        // alert('set attributes now working');

        const imgAttr =
            {
                height:50,
                source:"x",
                populateAttr: function () {
                    return this.height+ " " + this.source;
                    // alert('this is working');
                }
            }
        imgAttr.populateAttr();
    }.....
.....