Reputation: 4528
I have this code:
var my = {
vars: {
name: 'mojo'
},
secondLevel: {
vars: {
name: my.vars.name
}
},
};
$("#myDiv").text(my.vars.name);
I get this error:
Uncaught TypeError: Cannot read property 'vars' of undefined
Why can't I set name: my.vars.name
?
Upvotes: 1
Views: 109
Reputation: 5622
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
Upvotes: 0
Reputation: 15609
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);
Upvotes: 0
Reputation: 1942
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?
Upvotes: 3