0
var a = {
    b: {
        c: 1
    },
    d: this.b.c
};

Error:

this.b is undefined

How can I call b.c?

Gabriel Llamas
  • 18,244
  • 26
  • 87
  • 112
  • possible duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) – Felix Kling Dec 15 '11 at 11:57

2 Answers2

5
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

Matt
  • 74,352
  • 26
  • 153
  • 180
1

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
Community
  • 1
  • 1
KooiInc
  • 119,216
  • 31
  • 141
  • 177