user2297440
user2297440

Reputation: 47

Accessing variables in a javascript object

So I have an object:

settings: {
    navBar: $(".navbar");
    dropdown: navBar.find(".dropdown");
}

However this throws the error navBar is not defined. Using this.navBar does not seem to work either.

Any insight into why this isn't working and the proper way to access the variable would be much appreciated.

Upvotes: 1

Views: 93

Answers (2)

Marty
Marty

Reputation: 39458

You mean you're having trouble referring to sibling properties when you're defining an object, like this:

var example = {
    a: 1,
    b: a + 1 // <-- a is undefined
};

This is because a or this.a here would refer to the property a within the scope defining example.

You could try something like this:

function prepareSettings(navNode)
{
    return {
        navBar: navNode,
        dropdown: navNode.find(".dropdown")
    };
}

var settings = prepareSettings( $(".navbar") );

Or create a getter type method within settings, wherin this refers to the settings object and has access to its navBar property:

var settings = {
    navBar: $(".navbar"),
    getDropdown: function()
    {
        return this.navBar.find(".dropdown");
    }
};

A clearer example of the issue you're having could be demonstrated like so:

var a = 5;
var test = {
    a: 3,
    b: a
};


// Output is 5 rather than 3, which you might have
// been expecting instead.
console.log(test.b);

Upvotes: 3

Trevor Dixon
Trevor Dixon

Reputation: 24332

The navBar property can't be accessed from inside the object literal declaration. You'll have to do something like this:

var navBar = $(".navbar"),
    settings = {
        navBar: navBar,
        dropdown: navBar.find(".dropdown")
    };

Declare navBar as a local variable, then refer to it from inside your object declaration.

Upvotes: 1

Related Questions