Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
104
rated 0 times [  105] [ 1]  / answers: 1 / hits: 26638  / 11 Years ago, fri, september 6, 2013, 12:00:00

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?


More From » object

 Answers
18

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

[#75860] Thursday, September 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
saiget

Total Points: 64
Total Questions: 105
Total Answers: 105

Location: Belarus
Member since Tue, Mar 14, 2023
1 Year ago
;