1

I'm trying to figure out whether it is possible to get object name out of variable that is just pointing to it.

So lets say I have code like this:

var myObj = {
   content: "this is my object"
}

var pointer = myObj;
// any way to get "myObj" string from "pointer" variable?

var myFunc = function(parameter) {
   console.log(parameter)
   // any way to get "myObj" string from "parameter" variable inside function?
}
myFunc(myObj)

Any way to get original object name in Javascript as string rather than object itself?

Can it be done some other way if above methods cannot be used?

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
R1cky
  • 662
  • 5
  • 16

3 Answers3

3

myObj is not the original object name, but rather the name of the variable that holds a reference to your object. From that perspective, it is really no different than pointer.

To my knowledge, it is currently not possible to get the names of the variables holding a reference to an object from the object alone.

TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
-3

Hope it will help.

var myObj = {
   content: "this is my object"
   name : 'myobj'
}

var pointer = myObj;
// any way to get "myObj" string from "pointer" variable?
//string variable.
name = pointer.name;

var myFunc = function(parameter) {
   console.log(parameter.name)
   // any way to get "myObj" string from "parameter" variable inside function?
}
myFunc(myObj)
Pirate
  • 2,886
  • 4
  • 24
  • 42
  • Creating a JavaScript Object.

    It is working then why did you down vote?

    – Pirate Jul 14 '16 at 15:45
  • 1
    I mean, sure it works, so does `var x = 1 + 1`, but the code is not doing what was asked. – Kevin B Jul 14 '16 at 15:45
  • You have asked is it possible. And i have just show you a way to do that. – Pirate Jul 14 '16 at 15:47
  • well, no, your code stores the name of the variable somewhere else, and you get it from that rather than from the value, which is what was being asked. – Kevin B Jul 14 '16 at 15:48
  • that's indeed workaround I was thinking about and which I have as a plan B, but was hoping for some more neat solution – R1cky Jul 14 '16 at 16:07
-3

From what I understand you want to get the object name which is passed thru as a parameter, not the object value.

If so in myFunc do:

for (n in parameter) { console.log(n); }
dijipiji
  • 3,063
  • 1
  • 26
  • 21