1

I have this code:

var my = {    
  vars: {
    name: 'mojo'
  },

  secondLevel: {
    vars: {
      name: my.vars.name
    }
  },
};

$("#myDiv").text(my.vars.name);

fiddle

I get this error:

Uncaught TypeError: Cannot read property 'vars' of undefined 

Why can't I set name: my.vars.name?

1

3 Answers 3

3

You're accessing the variable that not yet have been created. Consider {} as constructor for an Object, so you're trying to work with object that have not yet been created. You can write it like this:

var my = {    
  vars: {
    name: 'mojo'
  },
  secondLevel: {
    vars: {}
  }
};

my.secondLevel.vars.name = my.vars.name;

$("#myDiv").text(my.vars.name);

By the way, why do you want that "second level" thing?

2
  • Ah ok I get it. Well I'm writing a huge js file (2000+ lines) and I want to have a section for vars in each "area", so vars doesn't get mixed and lose the overview.
    – MojoDK
    Jul 4, 2014 at 10:52
  • @MojoDK, you might wanna consider closures: stackoverflow.com/questions/111102/… Jul 4, 2014 at 10:54
0

Fiddle

You can not use . in the names.

But also you have it round the wrong way if you did want it to work.

It should be like this:

var my = {    
    vars: {
        name: 'mojo'
    },

    secondLevel: {
        vars: {
            name: my_vars_name
        }
    },
};

 $("#myDiv").text(my_vars_name);
0

Actually you get another error initially when js encounters your definition.

var my = {    
    vars: {
        name: 'mojo'
    },

    secondLevel: {
        vars: {
            name: my.vars.name//This is wrong. Use this.vars.name
        }
    },
};

TypeError: my is undefined

you didn't notice this error. You cannot reference my in my declartion.

my is undefined because of this and therefore you cannot reference it.

Use this instead of my

name:this.vars.name

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.