Return the property name from a nested object literal
Return the property name from a nested object literal
I have an object and I'm trying to get the name of the parent property of a method.
var a = b: c: function() return // I want "b"
var a = b: c: function() return // I want "b"
Is this possible?
How are you calling the function? Functions don't really "know" who has a reference to them.
– Mark Meyer
Aug 31 at 22:43
How do you call the function if you don't already have a reference to
a.b? What higher level problem are you trying to solve?– charlietfl
Aug 31 at 22:53
a.b
2 Answers
2
It's not possible. When a variable object contains a reference to a function, there's no reference in the reverse direction. There can also be multiple references, e.g.
var a = b: c: function() return // I want "b"
var x = y: z: a.b.c;
Now a.b.c and x.y.z are the same function, how would it know whether to return b or y?
a.b.c
x.y.z
b
y
Note, however, that when you call the function as
a.b.c()
it receives the value of a.b as the context in this. So you can do something like:
a.b
this
var a =
b:
c: function()
console.log(this.d);
,
d: 1
;
var x =
y:
z: a.b.c,
d: 10
;
a.b.c();
x.y.z();
This still doesn't help you get the property name b, though.
b
You could declare a function iterating the object that contains the function but we have to know the main object (in this case a).
To call that function, since we don't know b, we have to iterate the properties of a and the nested objects to find it.
var a = b: c: function() for(p in a)console.log(p)
for(p in a)
for(p2 in a[p])
a[p][p2]();
I'm probably forcing the rules because you didn't say anything about the main object (a), but the idea here is to start from the beginning and move along to reach the goal.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
You mean dynamically right?
– MinusFour
Aug 31 at 22:37