从对象中的函数中获取保存对象的变量的名称

Getting the name of variable which holds an object, from the function resides in the object

本文关键字:对象 变量 函数 获取 保存      更新时间:2023-09-26

假设一个对象声明如下

var object1 = {
    getName: function() {
        alert(name)
    }
};

是否有办法从getName警报"object1"

如果你声明一个像object literal这样的对象,那么答案是否定的,你不能得到变量名。但是,可以使用constructor:

声明它。
function Obj() {
    this.getName = function() {
        console.log(this.constructor.name);
    }
}
new Obj().getName(); // "Obj"