简体   繁体   中英

How to get the name of the variable containing the object in JavaScript

I can get the Class name of the Class with the code below:

 function MyClass() { return 42; } var obj = new MyClass(); console.log(obj.constructor.name);

But how to get the name of the variable?

You can't.

Consider:

function MyClass() {
    return 42;   
}

var obj = new MyClass();
var ob2 = obj;
var ob3 = obj;

There are now three variables all with the same value. Which one would you get if it was possible?

There's no reverse relationship between a variable and its value in JavaScript.

This question defeats itself to a great extent. The use case for this is usually when you scan an object for certain key/value pairs. And even in the event that you want to foster through all global/window variables, you can still do:

for(var obj_name in window) { 
  if(window.hasOwnProperty && !window.hasOwnProperty(obj_name)) continue;
  console.log(obj_name);
  if(window[obj_name]) console.log(window[obj_name]);
}

Try this

function MyClass() {
   return 42;   
}

var obj = new MyClass();
var name = /function (.{1,})\(/;
var results = (name).exec(obj.constructor);
if(results)
{
    console.log(results[1])
}

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