0

I have a JSON object with the following structure:

obj = {
    foo: 'bar',
    data: {
        hello: this.foo
    }
}

However, this in the 2nd level is always the Window object. How can I reference foo properly?

NOTE

I know I can put the object into a "class" and referencer the property with selfor something. This is not an option for me. The object must be a standalone JSON object.

dopatraman
  • 13,416
  • 29
  • 90
  • 154
  • The value of *this* within an execution context is set by the call. How are you attempting to access the property? I guess by "JSON object" you actually mean an [*Object initialiser*](http://ecma-international.org/ecma-262/5.1/#sec-11.1.5) or literal. – RobG Apr 12 '15 at 23:42
  • If `obj = {foo: 'bar',data: {}}; obj.data.hello = obj.foo;` isn't an option, I'm not aware of any way to do that in object declaration. – some Apr 12 '15 at 23:43
  • just to mention that the structure you have provided is a standard Javascript Object ... and second this depends on the context ... because it is in main context it is always window – Reflective Apr 12 '15 at 23:43
  • @Reflective—it depends on how *this* has been set **within** an execution context. – RobG Apr 12 '15 at 23:46
  • that's what i told :) in code provided it is executed in main context which is window – Reflective Apr 12 '15 at 23:48
  • @RobG this isnt a duplicate of that question. I'm not asking how to use the `this` keyword. I'm asking how to reference specific layers of an object. This question could very well have a difference answer than the "duplicate" you have linked to. – dopatraman Apr 12 '15 at 23:50
  • @dopatraman: I am not sure this question is entirely clear. Could you perhaps add a JS Fiddle to illustrate what you are trying to do, or add more code to the question? As it stands, the `this` value will vary depending on where this code is executed. – halfer Apr 12 '15 at 23:56
  • This question has at least 3 week points: 1) There's nothing related to JSON 2) duplicating data in data structures sooner ot later will lead you to inconsistency - wrong approach 3) you can not use slef- referencing of an stil undefined object - so you can not slef-reference an object in it's definition. It's clear. – Reflective Apr 12 '15 at 23:58
  • If this was on the same level you could use a getter like this: `obj=({foo:'bar', get data(){return this.foo;}})`. Because in your case `data` is its own object `this` can never reference the `obj` object inside `data`. – Sebastian Simon Apr 12 '15 at 23:58
  • @dopatraman—Bergi has changed the duplicate, whatever. There are two issues: attempting to use *this* in a context where it can't be set and attempting to reference object properties defined within the same object literal. – RobG Apr 13 '15 at 06:06

1 Answers1

0

Instead of this.foo, use obj.foo. Javascript almost always thinks this is the global/window. If that doesn't work, I would recommend creating another variable.

Good luck!