0

How can I obtain the name of the object I passed to a function, inside that function ?

var referencedObject = {
    someProperty : 'string'
};

var functionObject = {
    construct: function(reference){
        console.log(reference.toString());
    }
};

functionObject.construct(referencedObject);

I'm Looking for referencedObject as an output by the console.log();

Currently is giving me [object object]

  • I'm 99% confident you can't. That info is not available to the function at runtime. – Jaime Blázquez Feb 21 '20 at 14:17
  • You can't get the name of a variable, you would have to pass the name manually. Or alternatively - put the object in another object, and the name you desire to get as the key. – DaCurse Feb 21 '20 at 14:18
  • 1
    Taking a step back... Why do you need the *name* of the variable? What's the overall goal here? – David Feb 21 '20 at 14:19
  • 1
    Not possible to implement generically. Unless you dynamically perform a reverse lookup by crawling the stacktrace using an AST parser. Which is...not easy, to say the least. Also, this is very likely [an XY problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). Can you explain *why* you need this? What is the actual problem you're trying to solve? – VLAZ Feb 21 '20 at 14:21
  • You can do it, but this question is a duplicate – Greedo Feb 21 '20 at 14:21
  • 2
    Does this answer your question? [Variable name as a string in Javascript](https://stackoverflow.com/questions/4602141/variable-name-as-a-string-in-javascript) – Greedo Feb 21 '20 at 14:21
  • Thank you for the quick responses. Those solutions do not return the objects name. ||| So my options are: * Passing the object and a string name * Adding a name: property to the object * Putting the object in another object ||| I need this for a function that constructs HTML from a JS object that defines a 'layer', the objects name is required for the id tags of each div. For clean workings i'm going for the third option, and putting all my layers in an object, so i can access each layers name as the key. ||| Thank you all, you make this platform great ! – Michiel Celis Feb 21 '20 at 14:49

1 Answers1

0

You can't do that using '.toString()' method. Instead, you need JSON.stringify(your object). Therefore, your code should look something like this,

console.log(JSON.stringify(reference));

I hope that helps.

Md Sabbir Alam
  • 4,937
  • 3
  • 15
  • 30