Reputation: 128
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.
Upvotes: 2
Views: 869
Reputation: 4091
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/
Upvotes: 4