简体   繁体   中英

Traversing between parent / child properties in nested JSON objects in JavaScript

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.

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/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM