0

I know I can nest objects in objects and recall to them easily example:

var ex1 = {
    data1: 1,
    dataOb: {
        data1: 2,
        data2: ex1.data1 + ex1.dataO.data1,
    }
}

And I can do console.log(ex1.dataO.data1) but I can't recall from dataOb to ex1.data1 example: data2: ex1.data1 + dataOb.data1 doesn't work, so my question is it possible to recall from DataOb to parental object ex1 ?

Kara
  • 6,115
  • 16
  • 50
  • 57
Szarik
  • 17
  • 2
  • 8
  • Thanks, but still i can't recall to the ex1.data1 ; – Szarik Mar 27 '14 at 19:36
  • duplicate of [Self-references in object literal declarations](http://stackoverflow.com/questions/4616202/self-references-in-object-literal-declarations) - it's the same problem as for unnested objects. – Bergi Mar 27 '14 at 19:43
  • What are you talking about? You can't do that unless you've defined `ex1` earlier, i.e. you are redefining `ex1`. There is no such thing as "recall". – freakish Mar 27 '14 at 19:44

3 Answers3

0

No. At the time that you're defining data2, you're still in the middle of defining ex1. That is, it doesn't really exist yet. You're trying to access it before you've even finished defining it.

Kevin Ennis
  • 14,226
  • 2
  • 43
  • 44
0

If I understand you question rightly... do you want to use ex1.data1 in the same sentence you're creating the whole object?

This isn't ever possible!

You want to access to a reference that hasn't been created yet.

It's like doing this:

var a = a + 1;

How do you set the value of a plus 1 if a isn't declared already?!

Matías Fidemraizer
  • 63,804
  • 18
  • 124
  • 206
0

You can do something like this:

var ex1 = {
  data1: 1,
  dataOb: {
    data1: 2,
    data2: 4
  },
  getSum: function () {
    var sum = 0;
    for ( var i = 0; i < arguments.length; i++ ) {
      sum += arguments[i];
    }

    return sum;

  }
};

console.log(ex1.getSum(ex1.data1, ex1.dataOb.data1)); // should log 3
Seed
  • 744
  • 2
  • 10
  • 21
  • Not really clean, but you can even take `ex1.dataOb.data` and make that in a method that returns certain attributes within the object. so from your example, it could be `ex1.dataOb.data2 = function () {return ex1.data1 + ex1.dataOb.data2}` – Seed Mar 27 '14 at 20:19