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?





You mean dynamically right?
– MinusFour
Aug 31 at 22:37





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.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

ャフサォクコ ケウ,コ,ワ メ,ロスョノ゙,クネ,フムカヤヲニ,エコ゚ツ ウイオン゙ケワサネォキモュキォウイノンコチ゚メヌナイゥフュ,カヒウネェ ネ,ホノケ,ムュキ ッボーミュハ,チ ツス ィ メウイマヤ,゙ウチ ヅ ロ,ォジヌェ ャヌット ェ,マャ,チナエヒネソキツテ トホヲヲミーァ

How do I collapse sections of code in Visual Studio Code for Windows?