var a = {
b: {
c: 1
},
d: this.b.c
};
Error:
this.b is undefined
How can I call b.c?
var a = {
b: {
c: 1
},
d: this.b.c
};
Error:
this.b is undefined
How can I call b.c?
var a = {
b: {
c: 1
}
};
a.d = a.b.c;
Would be the only way. this.b.c
is executed in the scope where you're constructing the a
object, rather than within the object itself; therefore this
is equal to window
, and window.b == undefined
Although Matt told you there was only one way, this may be an alternative:
var a = {
b: {c: 1},
d: function(){return this.b.c;}
}
alert(a.d()); //=> 1
or
var a = {
b: {c: 1},
d: function(){if (this.d instanceof Function) {this.d = this.b.c;}}
}
a.d();
alert(a.d); //=> 1
or execute an anonymous function:
var a = function(){
var obj ={b: {c: 1}}
obj.d = obj.b.c;
return obj;
}();
alert(a.d); //=> 1