简体   繁体   中英

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" }}}

Is this possible?

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, eg

var a = {b: {c: function() {return // I want "b" }}}
var x = {y: {z: a.b.c}};

Now abc and xyz are the same function, how would it know whether to return b or y ?

Note, however, that when you call the function as

a.b.c()

it receives the value of ab as the context in this . So you can do something like:

 var a = { b: { c: function() { console.log(this.d); }, d: 1 } }; var x = { y: { z: abc, d: 10 } }; abc(); xyz(); 

This still doesn't help you get the property name b , though.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM