1

I'm wondering whether there is a way to access the name of an object within the object itself.

let object = {a: {test: ()=>{ console.log(?); }}}
object.a.test() // should give me 'a'

In this example I would like to print the name of the object ('a') in the console.log call.

mhu
  • 17,720
  • 10
  • 62
  • 93
herhuf
  • 497
  • 3
  • 17
  • 4
    That's not really a meaningful thing to do in JavaScript. The object (the value of `object.a`) doesn't have any real lasting relationship to that particular property of `object`; it just happens to be its value. It could be the value of any number of other properties of other objects, or variables. – Pointy May 06 '19 at 14:31
  • 2
    You already know it's name, "a", so why do you need to get it programmatically? (I think this is an XY problem, you should really show us your actual usecase) – Jonas Wilms May 06 '19 at 14:34
  • It's just something that might have been useful. But I guess I should rather restructure my program so I don't need this. – herhuf May 06 '19 at 14:39

1 Answers1

-2

You can use normal functions and loop through keys of the main parent object and check if its value is equal to this

let object = {
  a:{
    test: function(){ 
      console.log(Object.keys(object).find(x => object[x] === this)); 
    }
  }
}
object.a.test()
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
  • You're misusing the `this` keyword. It won't always work like you're expecting (e.g. try executing `(function () { object.a.test(); }())` instead). – Pedro Corso May 06 '19 at 14:42
  • @PedroCorso it will work if `object` is available – adiga May 06 '19 at 14:46
  • @adiga Sorry, bad example. But say that you want to pass `object.a.test` as a callback: `function callFunc(func) { func() }` and then call it as `callFunc(object.a.test)`. – Pedro Corso May 06 '19 at 14:55