0

I want to retrieve the variable name that I just created without passing it as an argument.

Eg:

  Var ObjName = function(hello) {

  ...

  }

  Var something = new ObjName(66)

How do I get the new variable to return it’s own declared name? Eg: something.this.name returns “something”.

As a side note, I’m not looking for something.constructor.name. I hope this makes sense. Thank you!

user1924218
  • 99
  • 1
  • 11
  • `Var` will result in a `SyntaxError`. – CertainPerformance Nov 03 '18 at 04:04
  • 2
    It's not possible without some really weird hacks, but a script shouldn't depend on the names of its variables. – CertainPerformance Nov 03 '18 at 04:06
  • The var was autocorrected – user1924218 Nov 03 '18 at 04:12
  • 1
    Possible duplicate of [Getting the object variable name in JavaScript](https://stackoverflow.com/questions/42870307/getting-the-object-variable-name-in-javascript) – Sebastian Simon Nov 03 '18 at 05:00
  • It’s close. But that method requires that I pass an argument to it. I wanted to kind of create a property in the object that would automatically store the created variable. Long story short I am developing a game engine with a scripting. But anytime a variable or object is created I need to know the name so I can make a save game file with all the data. – user1924218 Nov 03 '18 at 05:08
  • You never need or want unknown variable names. Please use an object instead: `const obj = {something: new ObjName(66)};` … `console.log(obj.something);`, or an array. As for _“I wanted to kind of create a property in the object that would automatically store the created variable”_, the answer already includes _“This is not possible in JavaScript.”_ – Sebastian Simon Nov 03 '18 at 05:57

1 Answers1

-1

the following code prints the variable name:

var something = 'diego'
Object.keys({something})[0] // prints "something
Diego Felipe
  • 386
  • 5
  • 19