javascript 如何使用 JS 将对象的名称转换为字符串形式?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18649195/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can i get a object's name into string form using JS?
提问by nice
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"?
我怎样才能得到 obj'name 到一个字符串“obj”?
回答by Barmar
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.
所有这些变量都引用同一个对象——它没有特定的名称。
回答by Rick Hanlon II
You can't access the name of the variable.
您无法访问变量的名称。
But, you could use the fact that functions are first-class objectsin 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:
但是,您可以利用函数是javascript 中的一流对象这一事实来为您带来优势,具体取决于您的用例是什么。由于每个函数对象都具有设置为函数名称的“name”属性,您可以执行以下操作:
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.
请注意,我分配了一个命名函数obj
而不是更常见的匿名函数——因为匿名函数没有名称值。
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 valueyou 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 returnedby 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 variablebecause you could assign obj
to another variable named jbo
:
请注意,此技术仍然不会为您提供变量的名称,因为您可以分配obj
给另一个名为 的变量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"