I have following code:
var objectParent:{
child1:{
test1:function(){},
test2:function(){}
},
child2:{
demo1:function(){},
demo2:function(){},
parent:this // gives child2
grandparent: .... // need to reference objectParent here
}
}
We can reference object by using this keyword, But what for grand object or i mean parent of parent object?
Now, i am using grandparent:objectParent to reference parent object
Is there other way like this selector to reference parentObject?
Are these my coding is bad,good or better?
I have following code:
var objectParent:{
child1:{
test1:function(){},
test2:function(){}
},
child2:{
demo1:function(){},
demo2:function(){},
parent:this // gives child2
grandparent: .... // need to reference objectParent here
}
}
We can reference object by using this keyword, But what for grand object or i mean parent of parent object?
Now, i am using grandparent:objectParent to reference parent object
Is there other way like this selector to reference parentObject?
Are these my coding is bad,good or better?
Share Improve this question edited Feb 23, 2013 at 3:45 blue ghhgdtt asked Feb 23, 2013 at 3:26 blue ghhgdttblue ghhgdtt 9214 gold badges11 silver badges16 bronze badges 5 |4 Answers
Reset to default 10If all your objects have a parent
property that refers to their parent, then can get the grandparent with object.parent.parent
.
It's not real clear what you're trying to do.
If you have an element reference elem
, then you can get its parent with elem.parentNode
. You can get a parent's parent (e.g. a grandparent) with elem.parentNode.parentNode
and so on.
If this isn't what you're trying to do, please explain in more detail what you mean by a grandparent object.
If you're not talking about DOM references at all and instead are asking about nested objects in plain javascript, then javascript does not contain any way to get the parent object that you are contained within. You would have to create a property on the child and set it if you need it that way after you've constructed the object (you can't set it with a static declaration either).
I had to do div.parentElement.parentElement
to achieve it.
One way to see what to access is by logging div.__proto__
to the console which shows you a long list of properties & methods you can call.
There's no need to go the long way doing div.parentNode.parentNode.parentNode
. Instead you can just do div.offsetParent
and you'll get the grandparent of the div.
var objectParent = { ... }
. – Barmar Commented Feb 23, 2013 at 3:49this
won't givechild2
, it returns whatever the value ofthis
is in the function you're running. You seem to be confusing object literals with object-oriented prototypes. – Barmar Commented Feb 23, 2013 at 3:50