1

I'm having a bit of an inception issue right now. I'm trying to reference an attribute of an object while creating another attribute of the object.

For example:

 var x = {
     a1 : "a",
     b2 : this.a1,
      c : "c"
 }

 alert(x.a1); // Returns properly
 alert(x.b2); // Returns undefined.

If I try to make b2 reference x.b2, it doesn't work either. Can anyone point me in the right direction?

All in all, I'm trying to decide the value of b2 based on the value of a1 without having to take another step out of the object.

Here's a fiddle -- http://jsfiddle.net/fpG9h/

streetlight
  • 5,968
  • 13
  • 62
  • 101

1 Answers1

0

You are most definitely in need of getters and setters. You can define them like this

var obj = {
    a1: "a",
    get b2() {
        return this.a1;
    },
    set b2(value) {
        this.a1 = value;
    },
    c: "c"
}

console.log(obj.b2);    // a
obj.b2 = "bbb";
console.log(obj.b2);    // bbb
console.log(obj.a1);    // bbb
thefourtheye
  • 233,700
  • 52
  • 457
  • 497