[英]is there such thing as function.name for objects
So I was wondering if there is a way to use function.name
but for objects. 所以我想知道是否有一种方法可以使用
function.name
而不是对象。 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/name https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Function/name
What I mean by this is to have something like this: 我的意思是要拥有这样的东西:
function myFunction() {}
console.log(myFunction.name); // logs "myFunction"
// but like
var myObj = {};
console.log(myObj.name); // logs "myObj"
and if it is possible, how would it handle something like this? 如果可能的话,它将如何处理这样的事情?
var myObj = {};
var myObj2 = {};
console.log(myObj2.name); // logs "myObj" or "myObj2" or both?
Two things 两件事情
Object
don't have name
property by default, unless you specify the same while defining the object, Object
没有name
属性,除非您在定义对象时指定了相同的属性, for example 例如
var myObj = {
name : "myObj"
};
myObj2.name
, myObj2
is not the name of the object, it is the name of reference (variable) to object. myObj2.name
, myObj2
不是对象的名称,而是对象的引用(变量)的名称。 Short answer? 简短的答案? No.
没有。
On the other hand, as you may know, global variables are part of window variable. 另一方面,您可能知道,全局变量是窗口变量的一部分。 Therefore, you could do something like:
因此,您可以执行以下操作:
function findName(obj, scope){
if(scope === void 0){
scope = window
}
for (prop in scope) {
if(scope.hasOwnProperty(prop) && scope[prop] == obj){
return prop
}
}
}
NOTE: This is extremly inefficent way to get variable name! 注意:这是获取变量名的极端无效的方法!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.