3

For example,I have a object here

var obj = {a:1,b:2,c:3}

how can i get obj'name to a String "obj"?

nice
  • 79
  • 1
  • 1
  • 7
  • See: http://stackoverflow.com/questions/789675/how-to-get-class-objects-name-as-a-string-in-javascript – Muhammad Talha Akbar Sep 06 '13 at 03:08
  • 4
    The object doesn't have a name. There is only a variable you defined that is a reference to that object in memory. And since you declared that variable yourself, you should know the name. So just do: `var myString = "obj";` – Steve Sep 06 '13 at 03:08
  • @nice why do you want to do that? – thefourtheye Sep 06 '13 at 03:55

2 Answers2

7

You can't. An object may be named by any number of variables, e.g.

var obj = {a:1,b:2,c:3};
var obj2 = obj;
var otherobj = obj2;

All these variables reference the same object -- it doesn't have a specific name.

Barmar
  • 741,623
  • 53
  • 500
  • 612
6

You can't access the name of the variable.

But, you could use the fact that functions are first-class objects in javascript to your advantage, depending on what your use case is. Since every function object has the "name" property which is set to the name of the function, you could do:

var obj = function obj(){ return {a:1,b:2,c:3}; };
console.log("obj.name is: " + obj.name);

> "obj.name is obj"

Notice that I assigned a named function to obj rather than the more common anonymous function--because anonymous functions do not have a name value.

var obj = function(){ return {a:1,b:2,c:3}; };
console.log("obj.name is: " + obj.name); 

> "obj.name is: "

So in this way you have an object with a name value accessible as a string. But there's a caveat. If you want to access the value you have to invoke the function:

console.log(obj());

> {a: 1, b: 2, c: 3}

This is because the variable is referencing a function, not the value returned by the function:

console.log(obj);

> function obj(){ return {a:1,b:2,c:3}; }

Note that this technique still doesn't give you the name of the variable because you could assign obj to another variable named jbo:

var obj = function obj(){ return {a:1,b:2,c:3}; };
console.log("obj.name is: " + obj.name);
var jbo = obj;
console.log("jbo.name is: " + jbo.name);

> "obj.name is obj"
> "jbo.name is obj"
Rick Hanlon II
  • 20,549
  • 7
  • 47
  • 53