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?
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?
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