1

I'm trying to access a value from the current value's parent but without success. I have these 2 sample javascript codes to demonstrate my issue:


1)

var x = {
    y : {
        a : "a",
        ab : this.a + "b"
    }
};

console.log(x.y);

> Object {
    a : a,
    ab : undefinedb
}

2)

var x = {
    y : {
        a : "a",
        ab : x.y.a + "b"
    }
};

console.log(x.y); // Uncaught TypeError: Cannot read property 'y' of undefined 
Adonis K. Kakoulidis
  • 4,951
  • 6
  • 34
  • 43
  • 2
    You cannot reference the object from inside the declaring object literal (conceptually, it *doesn't exist yet*). It must be done in two steps, or by using a function and deferred evaluation. –  Mar 08 '13 at 22:35

2 Answers2

2

When using literals, you can't until the statement that defines those variables is executed.

One good way is:

var x = {};

x.a = 'hey';

x.b = x.a + ' how you doing?';

alert(x.b);

Or more compactly:

var x = {
    a: 'hey'
};

x.b = x.a + ' how you doing?';

alert(x.b);
bgusach
  • 14,527
  • 14
  • 51
  • 68
1

x.y and this are undefined as at that point they are undefined. What I mean is that when you create an anonymous object it does not really exist until the closing }.

So another way to achieve what you want would be:

var x = {
     y : {a : "a"}
}

x.y.ab = x.y.a + "b"

This way the ab variable is being set after x and y have both been initialised, and therefore x.y.a is now set.

If you really want to set x.y.ab during initialisation then you would need to do it more formally with functions and closures. Something like the following.

var x = function(){
  this.a = 'foo';
  this.b = this.a + ' bar';
}() // Immediate function call so I don't have to create it.

console.log(x.b); // logs 'foo bar'
Coin_op
  • 10,568
  • 4
  • 35
  • 46