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?

Albzi
  • 15,431
  • 6
  • 46
  • 63
MojoDK
  • 4,410
  • 10
  • 42
  • 80
  • 3
    You cannot self-reference an object literal as this does: `name: my.vars.name` (there is no `my` at the point of use) - [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Alex K. Jul 04 '14 at 10:46

3 Answers3

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?

Vladislav Qulin
  • 1,872
  • 1
  • 17
  • 20
  • 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 04 '14 at 10:52
  • @MojoDK, you might wanna consider closures: http://stackoverflow.com/questions/111102/how-do-javascript-closures-work – Vladislav Qulin Jul 04 '14 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);
Albzi
  • 15,431
  • 6
  • 46
  • 63
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
SoWhat
  • 5,564
  • 2
  • 28
  • 59