1

I'm not sure if "parent object" or even "property" are the correct terminology, so hopefully you will be able to understand.

var parentObj = {
  x: 1,
  childObj: {
    x: 2,
    childX: this.x, //2
    parentX: ?????? //1
  }
}

Is there any way to get the value of the parent's X value. I know that I could just use ParentObj.x, but is there a way to get the value regardless of what the parent's name is?

Thanks.

koninos
  • 4,969
  • 5
  • 28
  • 47
Polygon
  • 265
  • 1
  • 2
  • 12
  • 1
    Nope, not really, there's no special keyword to get the "parent" object, and there's no special scope in object literals either, so `this` would just be the surrounding scope, whatever that is. – adeneo May 10 '16 at 20:52
  • Can you explain why you don't want to use ParentObj.x? – Tyler May 10 '16 at 20:57
  • This doesn't make sense at all. Accessing the "parent" seems to be your smallest problem. Have a look at [Creating an nested array from an object fails](http://stackoverflow.com/q/4616202/218196) – Felix Kling May 10 '16 at 20:58
  • One thing to consider is your naming convention. Normally when we use 'parent' and 'child' we are talking about class inheritance. In this case you are not using class inheritance you are using class collaboration. When using inheritance there is a 'super' keyword which the child may use to access traits of the parent. – nurdyguy May 10 '16 at 21:06
  • @FelixKling oops. The way I have it in my program is different. I just did it that way to make it more simple. – Polygon May 10 '16 at 21:11
  • @nurdyguy Thanks. As I said, I wan't quite sure about the names. – Polygon May 10 '16 at 21:12
  • 1
    Well, you should provide an example that represents your use case, because there have been quite a few similar posts yours could be a duplicate of: https://stackoverflow.com/search?q=%5Bjavascript%5D+access+parent+object . – Felix Kling May 10 '16 at 21:18

1 Answers1

0

No, there is not a built in way to do that.

You would have to create a seed in order to have that type of "navigation property" available.

function seedParent(obj,top){
    obj["parentObj"] = top || this;
    for(var key in obj){
        if(toString.call(obj[key]) == toString.call({}))
            seedParent(obj[key],obj);
    }
}

Something like this work. And then you could use childObj.parentObj.x if you wanted.

Travis J
  • 81,153
  • 41
  • 202
  • 273