[英]Getting the name of variable which holds an object, from the function resides in the object
Suppose an object is declared as follows 假设对象声明如下
var object1 = {
getName: function() {
alert(name)
}
};
Is there a way to alert "object1"
from getName
? 有没有一种方法可以从
getName
警报"object1"
?
If you declare an object like object literal then the answer is no, you can't get variable name. 如果声明像对象文字这样的对象,那么答案是否定的,那么您将无法获得变量名。 You can however declare it using constuctor:
但是,您可以使用constuctor进行声明:
function Obj() {
this.getName = function() {
console.log(this.constructor.name);
}
}
new Obj().getName(); // "Obj"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.