[英]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. 我有一个json对象,其属性是一个嵌套的json。 The nested json has a function as a property.
嵌套的json具有作为属性的功能。 I want to access a property in that outer json from that function in that inner json.
我想从该内部json中的函数访问该外部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
. 我想从
nestedJson
getName
访问name
。 Is it possible? 可能吗? Is there any parent child traversing mechanism/way in json and nested json objects in javascript?
json和javascript中的嵌套json对象中是否有任何父子遍历机制/方式?
Thanks in advance. 提前致谢。
This is a POJO (Plain Old JavaScript Object), not JSON. 这是一个POJO(普通的旧JavaScript对象),而不是JSON。
The context of this
inside nestedJson.getName()
is different than the context of this
inside the first-level .getName()
. 的上下文中
this
内部nestedJson.getName()
比的上下文中不同this
一级内.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
. 由于将在该函数存在时定义该对象,因此您可以使用该对象本身来代替
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/
阅读此: http : //www.phpied.com/3-ways-to-define-a-javascript-class/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.