2

I have a json object and a property of which is a nested json. The nested json has a function as a property. I want to access a property in that outer json from that function in that inner json.

Let me explain with a dummy code,

{
  name: "Barry Allen",
  getName: function () { 
      return this.name; //this is returning "Barry Allen", which is fine
    },
  nestedJson: {
    getName: function () {
      //here I want something like return this.parent.name
    }
   }  
}

I want to access name from getName of nestedJson. Is it possible? Is there any parent child traversing mechanism/way in json and nested json objects in javascript?

Thanks in advance.

TruthSeeker
  • 128
  • 12

1 Answers1

4

This is a POJO (Plain Old JavaScript Object), not JSON.

The context of this inside nestedJson.getName() is different than the context of this inside the first-level .getName(). Since this object will already be defined by the time this function exists, you can use the object itself as a replacement for this.

var person = {
   name: "Some Guy",
       getName: function () { 
       return this.name;
   },
   nested: {
       getName: function () {
           return person.name;
       }
   }  
};

var try1 = person.getName();
var try2 = person.nested.getName();

console.log('try1', try1);
console.log('try2', try2);

That being said, I'd turn this into a different type of object. Read this: http://www.phpied.com/3-ways-to-define-a-javascript-class/

Mike
  • 4,071
  • 21
  • 36
  • 1
    Nice Approach. One thing, `this` inside `nested.getName()` should be whatever on the left side of `getName()`, in this case, it is `nested` object, not `window` – Z.Z. May 18 '16 at 14:39
  • Thanks for the answer @Mike, Also thanks for the link, I will read it. But changing the object structure is not in my hand. I didn't write it :P – TruthSeeker May 18 '16 at 14:51