1

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.

3
  • Try var navBar = $(".navbar"); ... ... settings: { navBar: navBar; dropdown: navBar.find(".dropdown"); } Commented May 28, 2013 at 3:52
  • It's because you don't even have an object there. Commented May 28, 2013 at 3:52
  • You need to show more code for us to actually help you Commented May 28, 2013 at 3:55

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you, this explains it for me. I didn't know you couldn't access sibling variables. While annoying, at least I'm not doing anything stupid which is a relief.
@user2297440 It might seem annoying at the moment, but as you progress you'll eventually realize it makes complete sense.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.