1

Possible Duplicate:
Access parent's parent from javascript object

Im a bit confused how to say this but i want what i would expect from the code "this.this.".

In the array

Foo = 
{
    bar : 
    {
        Tool : function()
        {
            return this.this.foofoo;
        },
    },
    foofoo : "rawr"
}

From the function Foo.bar.Tool() how can i get it to access the data foofoo ?

Thankyou !

Community
  • 1
  • 1
kjones1876
  • 762
  • 2
  • 10
  • 17

3 Answers3

3

I'm afraid you can't.

this doesn't work like you might expect -- it refers to the object that you're calling the function on behalf of, and has nothing to do with where the function was defined.

So for example:

var blah = { prop: 'blahprop' };
var cow = {
   cowfunc: function() {
       alert(this.prop);    // Notice there's no 'prop' in cow
   }
};

blah.blahfunc = cow.cowfunc;
blah.blahfunc();         // alerts 'blahprop'

If you want that behaviour, you'll need to pass in foofoo (or its parent).

Alternatively, you can initialize Foo as in your question, then set a reference on bar to Foo:

Foo.bar.Foo = Foo;

Then, assuming you're calling Tool on bar, you can change Tool to read:

Tool: function() {
    return this.Foo.foofoo;   // 'this' refers to bar when called like bar.Tool()
}
Cameron
  • 96,106
  • 25
  • 196
  • 225
1

Just reference the parent object literally:

Foo = 
{
    bar : 
    {
        Tool : function()
        {
            return Foo.foofoo;
        },
    },
    foofoo : "rawr"
}

alert(Foo.bar.Tool()); // alerts "rawr"
AlienWebguy
  • 76,997
  • 17
  • 122
  • 145
0

In JavaScript, variables (and properties of objects) reference values; they do not contain them. consider this code:

var foo = { message:"hello" };
var bar1 = { o:foo };
var bar2 = { b:foo };

In the above, bar1.o is the same object as bar2.a. Both you might consider the "parent" of foo, which is there is no information on the name or ownership of any value.

You cannot do what you want with the data structure you have. You need to either provide explicit pointers back to the "parent", or use a closure around a local variable.

Phrogz
  • 296,393
  • 112
  • 651
  • 745