![](/img/trans.png)
[英]How to obtain the variable name which holds an object instance from within the object : Javascript
[英]Getting the name of variable which holds an object, from the function resides in the object
假设对象声明如下
var object1 = {
getName: function() {
alert(name)
}
};
有没有一种方法可以从getName
警报"object1"
?
如果声明像对象文字这样的对象,那么答案是否定的,那么您将无法获得变量名。 但是,您可以使用constuctor进行声明:
function Obj() {
this.getName = function() {
console.log(this.constructor.name);
}
}
new Obj().getName(); // "Obj"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.